I have to convert the below string in DateTime. I have used following code for that but it was not working.
DateTime created = DateTime.ParseExact("Sun Feb 23 2014 00:00:00 GMT+0550", "ddd mmm d yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
My string to which I have to convert in Date Time is--
Sun Feb 23 2014 00:00:00 GMT+0550
I would parse this as a DateTimeOffset
instead of a DateTime
- after all, that's the data you've been given. Assuming it's always specified using GMT+...
you can use a format string of "ddd MMM d yyyy HH:mm:ss 'GMT'zzz"
. In particular, note:
MMM
is abbreviated month name, not mmm
'GMT'
will always match the letters 'GMT'zzz
is a UTC offset including minutes. It would be formatted with a colon, but apparently it's permissive enough without the colon being specified.Sample code:
using System;
using System.Globalization;
class Test
{
static void Main()
{
var dto = DateTimeOffset.ParseExact
("Sun Feb 23 2014 00:00:00 GMT+0550",
"ddd MMM d yyyy HH:mm:ss 'GMT'zzz",
CultureInfo.InvariantCulture);
Console.WriteLine(dto); // 23/02/2014 00:00:00 +05:50
}
}
See more on this question at Stackoverflow