user1031034
user1031034

Reputation: 856

Parse Javascript date to C# DateTime

I have date object in JavaScript which give me: "Wed Oct 01 2014 00:00:00 GMT+0200";

I try to parse it but I get an exception:

string Date = "Wed Oct 01 2014 00:00:00 GMT+0200";
DateTiem d = DateTime.ParseExact(Date,
                                 "ddd MM dd yyyy HH:mm:ss GMTzzzzz", 
                                 CultureInfo.InvariantCulture);

Upvotes: 3

Views: 1802

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98740

MM format specifier is 2 digit month number from 01 to 12.

You need to use MMM format specifier instead for abbreviated name of month.

And for your +0200 part, you need to use K format specifier which has time zone information instead of zzzzz.

And you need to use single quotes for your GMT part as 'GMT' to specify it as literal string delimiter.

string s = "Wed Oct 01 2014 00:00:00 GMT+0200";
DateTime dt;
if(DateTime.TryParseExact(s, "ddd MMM dd yyyy HH:mm:ss 'GMT'K", 
                          CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt);
}

Any z format specifier is not recommended with DateTime parsing. Because they represents signed offset of local time zone UTC value and this specifier doesn't effect DateTime.Kind property. And DateTime doesn't keep any offset value.

That's why this specifier fits with DateTimeOffset parsing instead.

Upvotes: 7

Related Questions