Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string format to datetime in mm/dd/yyyy

Tags:

c#

datetime

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.

like image 969
Aviral Kumar Avatar asked Apr 06 '12 11:04

Aviral Kumar


People also ask

How do I convert a string to a datetime?

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.

How convert dd mm yyyy string to date in Javascript?

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.

How do I change the date format from dd mm yyyy to dd mm yyyy?

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.


1 Answers

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); 
like image 165
Darbio Avatar answered Sep 29 '22 13:09

Darbio