Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 864
user1031034 Avatar asked Mar 03 '26 06:03

user1031034


1 Answers

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.

like image 125
Soner Gönül Avatar answered Mar 05 '26 18:03

Soner Gönül



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!