views:

666

answers:

3

I have javascript date object which gives me a date string in this format, "Wed Dec 16 00:00:00 UTC-0400 2009".

I pass this via Ajax to the server (ASP.NET c#)

How can I convert, "Wed Dec 16 00:00:00 UTC-0400 2009" to a C# DateTime object. DateTime.Parse fails.

A: 

To be honest I wouldn't try to parse that date string in C#, I'd personally try to create a more useful date structure from your javascript date object.

For instance you could use parse() in javascript which will return the ms representing the date object, which you can use DateTime.Parse() on to convert into a C# DateTime object.

Jay
+10  A: 

You can use DateTime.ParseExact which allows you to specify a format string to be used for parsing:

DateTime dt = DateTime.ParseExact("Wed Dec 16 00:00:00 UTC-0400 2009",
                                  "ddd MMM d HH:mm:ss UTCzzzzz yyyy",
                                  CultureInfo.InvariantCulture);
dtb
+1 I didn't realise you could do this, very cool :)
Jay
+5  A: 

The most reliable way would be to use milliseconds since the epoch. You can easily get this in JavaScript by calling Date.getTime(). Then, in C# you can convert it to a DateTime like this:

long msSinceEpoch = 1260402952906; // Value from Date.getTime() in JavaScript
return new DateTime(1970, 1, 1) + new TimeSpan(msSinceEpoch * 10000);

You have to multiply by 10,000 to convert from milliseconds to "ticks", which are 100 nanoseconds.

Evgeny