Categories
ajax asp.net jquery json

How do I format a Microsoft JSON date?

2123

I’m taking my first crack at Ajax with jQuery. I’m getting my data onto my page, but I’m having some trouble with the JSON data that is returned for Date data types. Basically, I’m getting a string back that looks like this:

/Date(1224043200000)/

From someone totally new to JSON – How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I’ve tried the jQuery.UI.datepicker plugin using $.datepicker.formatDate() without any success.

FYI: Here’s the solution I came up with using a combination of the answers here:

function getMismatch(id) {
  $.getJSON("Main.aspx?Callback=GetMismatch",
    { MismatchId: id },

    function (result) {
      $("#AuthMerchId").text(result.AuthorizationMerchantId);
      $("#SttlMerchId").text(result.SettlementMerchantId);
      $("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
      $("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
      $("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
      $("#LastUpdatedBy").text(result.LastUpdateNt);
      $("#ProcessIn").text(result.ProcessIn);
    }
  );

  return false;
}

function formatJSONDate(jsonDate) {
  var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
  return newDate;
}

This solution got my object from the callback method and displayed the dates on the page properly using the date format library.

5

  • 27

    This might be interesting: hanselman.com/blog/…

    – citronas

    Mar 16, 2012 at 10:32

  • 10

    The /Date(…)/ format is specific to Microsoft’s built-in JSON Date format – it’s not part of any standard, and JSON, coming from Javascript, has a standard: The ISO format Javascript specifies: stackoverflow.com/a/15952652/176877 So, this question is specific to Microsoft’s JSON Date format. I modified the title to clarify this.

    Jun 23, 2014 at 7:48

  • 1

    Use Newtonsoft JSON on the .NET side and to have nice typed values on the JS side, just use: github.com/RickStrahl/json.date-extensions

    – baHI

    May 11, 2017 at 16:54

  • You could use JSON++ instead of JSON. JSON++ is the same than JSON but with support for JavaScript types such as Date.

    – brillout

    Nov 14, 2018 at 11:06

  • Advice:: the official date format when you are using Json or XML is “yyyy-MM-dd”, try to use this format where ever you are writing the API or consume it.

    Jul 4, 2021 at 22:31

1748

eval() is not necessary. This will work fine:

var date = new Date(parseInt(jsonDate.substr(6)));

The substr() function takes out the /Date( part, and the parseInt() function gets the integer and ignores the )/ at the end. The resulting number is passed into the Date constructor.


I have intentionally left out the radix (the 2nd argument to parseInt); see my comment below.

Also, I completely agree with Rory’s comment: ISO-8601 dates are preferred over this old format – so this format generally shouldn’t be used for new development.

For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:

var date = new Date(jsonDate); //no ugly parsing needed; full timezone support

19

  • 5

    @Broam: Both methods (the replace function and this answer) would have to change if MS changes the format.

    Aug 25, 2010 at 16:11


  • 24

    Could you please update it with the radix var date = new Date(parseInt(jsonDate.substr(6), 10));

    Apr 25, 2012 at 5:25


  • 6

    @JamesKyburz: Every rule has exceptions, and I think this is when an exception applies. The JSON date numbers from .NET never have a leading “0”, so we can safely leave out the radix.

    Dec 20, 2012 at 17:49


  • 24

    It’s worth noting that this date format is pretty bad and the general move is to ISO-8601 formatted dates in JSON. See hanselman.com/blog/…

    – Rory

    Jan 28, 2013 at 11:20

  • 4

    This approach fails to consider timezone so can cause serious problems when your server and users are in different timezones. I posted an answer below that explains a very quick and easy way to deal with it on WCF and Javascript sides: stackoverflow.com/a/10743718/51061

    May 8, 2013 at 17:45

136

You can use this to get a date from JSON:

var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));

And then you can use a JavaScript Date Format script (1.2 KB when minified and gzipped) to display it as you want.

14

  • 8

    There’s nothing wrong with the line, the sequence is \// . First slash is escaped so it does not count like a comment. It’s your editor tricking you, the line will work fine.

    Aug 27, 2009 at 15:19

  • 154

    @rball, nonsense: jsonDate = new Date(+jsonDate.replace(/\/Date\((\d+)\)\//, '$1'));

    Jan 19, 2010 at 5:02


  • 40

    pst was correct, it is possible to do this in a variety of ways without ‘eval’. Crockford says that ‘eval Is Evil’ because it is less readable and is less secure, furthermore he may further imply that it is less efficient and more dangerous because it hits the javascript compiler.

    Feb 25, 2010 at 15:43


  • 14

    @Edy: new Function is almost as bad as eval: dev.opera.com/articles/view/efficient-javascript/…

    Sep 21, 2010 at 11:55

  • 6

    @Edy: That is another form of eval, and is just as ‘evil’. Parse the string instead (see my answer below)

    Jun 23, 2011 at 21:15

102

For those using Newtonsoft Json.NET, read up on how to do it via Native JSON in IE8, Firefox 3.5 plus Json.NET.

Also the documentation on changing the format of dates written by Json.NET is useful:
Serializing Dates with Json.NET

For those that are too lazy, here are the quick steps. As JSON has a loose DateTime implementation, you need to use the IsoDateTimeConverter(). Note that since Json.NET 4.5 the default date format is ISO so the code below isn’t needed.

string jsonText = JsonConvert.SerializeObject(p, new IsoDateTimeConverter());

The JSON will come through as

"fieldName": "2009-04-12T20:44:55"

Finally, some JavaScript to convert the ISO date to a JavaScript date:

function isoDateReviver(value) {
  if (typeof value === 'string') {
    var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(?:([\+-])(\d{2})\:(\d{2}))?Z?$/.exec(value);
      if (a) {
        var utcMilliseconds = Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);
        return new Date(utcMilliseconds);
      }
  }
  return value;
}

I used it like this

$("<span />").text(isoDateReviver(item.fieldName).toLocaleString()).appendTo("#" + divName);

3

  • 6

    The JavaScript Date constructor can parse the string for you: new Date("2009-04-12T20:44:55")

    Jun 19, 2013 at 18:00

  • 5

    Warning – The Date() Constructor formats and parsing are non-standard before ECMAScript 6. For example, IE 9 treats the date you give the constructor as a local time even if it is in IS0-8601 whichs is implied as UCT everywhere else. Don’t rely on the date constructor if you support older browsers. codeofmatt.com/2013/06/07/…

    – DanO

    Sep 22, 2014 at 17:56


  • Sending non-UTC date will sooner or later get you into trouble.

    – tymtam

    Jul 17, 2016 at 22:59