I have to convert string in mm/dd/yyyy format to datetime variable but it should remain in mm/dd/yyyy format.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Please help.
We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.
To convert a dd/mm/yyyy string to a date:Pass the year, month minus 1 and the day to the Date() constructor. The Date() constructor creates and returns a new Date object.
Your answer First, pick the cells that contain dates, then right-click and select Format Cells. Select Custom in the Number Tab, then type 'dd-mmm-yyyy' in the Type text box, then click okay. It will format the dates you specify.
You are looking for the DateTime.Parse()
method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01/01/2001");
Which will give you a DateTime
typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact
(MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "dd/MM/yyyy" } var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With