Tono Nam
Tono Nam

Reputation: 36058

JSON.net deserialize date with javascript

When I serialize a date using Json.Net I get the date formatted as:

'2015-07-07T17:27:00.057'

once I receive that object from ajax it comes as a string not as a date. How can I convert '2015-07-07T17:27:00.057' to a javascript date.

I have tried

 new Date('2015-07-07T17:27:00.057') but that gives the incorrect date

Edit:

Found the problem. If I serialize DateTime.Now I get the wrong date. But if I serialize DateTime.UtcNow I get the correct date when deserializing. I need to save my dates in Coordinated Universal Time (UTC). The comments were the solution, thanks so much.

Upvotes: 0

Views: 3281

Answers (3)

Ryan Wheale
Ryan Wheale

Reputation: 28410

The problem is that you need the timezone information encoded in the string. Try using DateTimeOffset.Now for a portable time format.

Also check out:

Upvotes: 1

ItsVeryWindy
ItsVeryWindy

Reputation: 36

Json.Net supports multiple ways of formatting a date, if your only consuming it from an ajax call you may want to look into JavaScriptDateTimeConverter.

http://www.newtonsoft.com/json/help/html/DatesInJSON.htm

Upvotes: 2

JamieD77
JamieD77

Reputation: 13949

try

new Date(JSON.parse(datestr));

Upvotes: -1

Related Questions