Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internet Explorer, Json.Net JavaScript date and milliseconds issue

I'm not sure if it's me missing something - or IE or Json.Net.

But basically this works:

new Date("2012-08-03T12:36:54.743Z")

This fails with 'Invalid Date' error:

new Date("2012-08-03T12:36:54.74Z")

The second date is stored in SQL Server as:

2012-08-03 12:36:54.740

It is then serialised as JSON using Json.Net - Json.Net did serialised the date as 2012-08-03T12:36:54.74Z, effectively chopping off the last 0.

My question(s):

  • Is this an intended behavior in IE - that it needs to have all 3 digits in the milliseconds bit to work ?
  • Is this an intended behavior in Json.Net - that it'll always chop off the last 0 in a date ?
like image 401
YS. Avatar asked Aug 03 '12 04:08

YS.


2 Answers

I can't tell you whether it is intended or not, but I've done a lot of searching and I haven't found a real solution for this issue neither. It seems that we have to accept the fact that IE only accepts exactly three digits. The only way (for me) to get around this issue is to use a custom converter for Json.NET when serializing:

string json = JsonConvert.SerializeObject(
    whatEver,
    new IsoDateTimeConverter
        {
            DateTimeFormat = "yyyy-MM-dd\\THH:mm:ss.fffK"
        }
    );

(only tested with Json.NET 4.0.8 and 4.5.8)

This forces Json.NET to use exactly 3 decimal places.

As far as I can tell, Json.NET serializes DateTime values in ISO format with the maximum necessary precision omitting trailing zeroes in the decimal places of the "second" value.

This matches the output of

someDateTimeValue.ToString("yyyy-MM-dd\\THH:mm:ss.FFFFFFFK")
  • A normal DateTime like DateTime.UtcNow will be serialized with up to 7 digits, because that is the precision of a DateTime (measured in Ticks).
  • If the "second" part of the DateTime has less decimal places, Json.NET omits those trailing zeroes.
  • A date value like DateTime.Today will therefore contain no digits behind the "second" value because it is exactly 0.

See also this description of custom date and time format strings.

like image 85
fero Avatar answered Nov 03 '22 00:11

fero


It's IE. The most comprehensive explaination and answer I found is at JavaScript: Which browsers support parsing of ISO-8601 Date String with Date.parse

In particular

IE9 was failing on milliseconds with digit counts other than 3: (fixed in IE10)

like image 24
RockResolve Avatar answered Nov 02 '22 23:11

RockResolve