Search code examples
c#stringdatetimetypeconverter

Converting string to DateTime


Possible Duplicate:
Date time format from string?

Does anyone know how I could convert the following string to a DateTime value in C# ?

"Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)"

Solution

  • If you only have strings ending with "GMT+0300 (E. Africa Standard Time)", you can try:

    string dateString = "Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)";
    DateTime date = DateTime.ParseExact(dateString, "ddd MMM dd yyyy HH:mm:ss 'GMT+0300 (E. Africa Standard Time)'", System.Globalization.CultureInfo.InvariantCulture);
    

    The meanings of the specifiers are as follows:

    • "ddd" The abbreviated name of the day of the week.
    • "MMM" The abbreviated name of the month.
    • "dd" The day of the month, from 01 through 31.
    • "yyyy" The year as a four-digit number.
    • "HH" The hour, using a 24-hour clock from 00 to 23.
    • "mm" The minute, from 00 through 59.
    • "ss" The second, from 00 through 59.
    • ":" The time separator.
    • "string", 'string' Literal string delimiter.

    You can find out more about different format specifiers in the MSDN article named Custom Date and Time Format Strings

    Moreover, if you want to parse "GMT+0300 (E. Africa Standard Time)" part too, I think you should implement a way to parse them yourself. I don't think there's a specifier for that.