views:

1313

answers:

5

How do I convert a string to DateTime format? For example, if I had a string like:

"24/10/2008"

How do I get that into DateTime format ?

+10  A: 

Use DateTime.ParseExact:

string str = "24/10/2008";
DateTime dt = DateTime.ParseExact(str, "dd/MM/yyyy", 
                                  Thread.CurrentThread.CurrentCulture);

(You should consider what culture you actually want to parse it in, admittedly.)

EDIT: Other answers have specified "null" as the third parameter - this is equivalent to using Thread.CurrentThread.CurrentCulture.

For other formats, see "Custom Date and Time Format Strings" in MSDN.

Jon Skeet
A: 

Try something like

DateTime date = System.DateTime.ParseExact(str, "dd/MM/yyyy", null);

For time this might work

DateTime date = System.DateTime.ParseExact(str, "HH:mm:ss", null);
Michal Sznajder
A: 
string str = "24/10/2008";
DateTime dt = Convert.ToDateTime(str);
+4  A: 

If you don't know the format, use:

DateTime d = DateTime.Parse(dateString);

This tries to parse the string representation of a date and time using the formatting rules of the current culture (e.g. English (US) "en-US", German "de-DE", ...). It tries to ignore unrecognized data, and fills in missing values for year, month and day with the current date (if parsing only a string containing the time for example).

If you know that the used culture of the string is different from the current one, you can specify the culture to use:

CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
DateTime d = DateTime.Parse(dateString, culture);

You should allways suround the conversion by a try-catch block since the string must conform to a recognized pattern. Alternatively, you can also test the validity of the string with the method DateTime.TryParse(dateString, out dateTime) which returns true on success and the result in dateTime; or false otherwise.

If you know the exact format, you can use

DateTime d = DateTime.ParseExact(dateString, "dd/MM/yyyy", null);

(See Custom Date and Time Format Strings from the MSDN site for other format strings).

mr_georg
+3  A: 

I'd also suggest looking at DateTime.TryParse if you aren't sure what format the date string will be in. This way you can avoid handing very expensive exceptions in the Parse routine.

I'd also second Jon Skeet's recommendation to use DateTime.ParseExact if you do know exactly what format the date will be in, every time.

Jeff Atwood
There's also .TryParseExact(), to get the best of both worlds.
Joel Coehoorn