Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing DateTime strings

I'm having some difficulties parsing strings of DateTime using DateTime.ParseExact.

    DateTime result;
    CultureInfo provider = CultureInfo.InvariantCulture;

    // Parse date-only value with invariant culture.
    //format = "mm/dd/yyyy";
format = "d";
    try
    {

        result = DateTime.ParseExact(data+" 12:00:00 AM", format, provider);
    }

data is a string variable loaded with dates of the format "5/20/2009". I tried tacking on a fake time just to see if that would work, and it didn't(with or without the tack on). I also tried using the "g" format specifier and it did not work, I always get the exception that it isn't a valid DateTime string. The only dates it works for is like "12/20/2009" (notice that 2 digits in the "MM" part)

I can not get this routine to work with single digit months! Microsofts own example from MSDN is

6/15/2009 1:45:30 PM -> 6/15/2009 (en-US)

and it will not work with this. I am just not understanding what I am doing wrong. I have also tried my own format specifiers like "mm/dd/yyyy" and "MM/dd/yyyy" but to no avail.

like image 620
Earlz Avatar asked Dec 23 '22 09:12

Earlz


1 Answers

If you want to parse a DateTime in en-US format, you have to specify the en-US culture:

DateTime.ParseExact("6/15/2009", "d", CultureInfo.GetCultureInfo("en-US"));
like image 108
dtb Avatar answered Dec 30 '22 19:12

dtb