2153

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark Struzinski
  • 32,945
  • 35
  • 107
  • 137
  • 27
    This might be interesting: http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx – citronas Mar 16 '12 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: http://stackoverflow.com/a/15952652/176877 So, this question is specific to Microsoft's JSON Date format. I modified the title to clarify this. – Chris Moschini Jun 23 '14 at 07:48
  • 1
    Use Newtonsoft JSON on the .NET side and to have nice typed values on the JS side, just use: https://github.com/RickStrahl/json.date-extensions – baHI May 11 '17 at 16:54
  • You could use JSON++ instead of JSON. [JSON++](https://github.com/brillout/jpp) is the same than JSON but with support for JavaScript types such as `Date`. – brillout Nov 14 '18 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. – Ahmad Hindash Jul 04 '21 at 22:31

42 Answers42

1760

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
Roy Tinker
  • 10,044
  • 4
  • 41
  • 58
  • The replace function is safer in case MS decides to change the format. – Broam Aug 24 '10 at 19:50
  • 5
    @Broam: Both methods (the replace function and this answer) would have to change if MS changes the format. – Roy Tinker Aug 25 '10 at 16:11
  • @RoyTinker: Does this work with the +- suffixes found sometimes like 1224043200000-0600 – whitneyland Feb 21 '12 at 23:36
  • 3
    @LeeWhitney: Yes, but it will ignore the suffix (which is a timezone offset). The parseInt function grabs numerals from the front of the string passed to it until it encounters a non-numeral character or the end of the string, at which point it stops and returns the numeric result. – Roy Tinker Feb 22 '12 at 17:13
  • 24
    Could you please update it with the radix var date = new Date(parseInt(jsonDate.substr(6), 10)); – James Kyburz Apr 25 '12 at 05:25
  • 1
    Parseint without a radix is a crime! Please add the radix. – Trident D'Gao Nov 03 '12 at 22:32
  • 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. – Roy Tinker Dec 20 '12 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 http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx – Rory Jan 28 '13 at 11:20
  • Good answer, its a universal issue, I did it for me in following manner: var myStrDt = new Date(parseInt(myJSONDate.substr(6))).asString(); alert(myStrDt); – Gaurav Arora Mar 20 '13 at 19:59
  • 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: http://stackoverflow.com/a/10743718/51061 – Scott Willeke May 08 '13 at 17:45
  • This is a very nice way but there are some timezones where this code will not work correctly. – Misha Zaslavsky Oct 18 '13 at 19:32
  • 3
    @MishaZaslavsky: Generally, this format shouldn't be used for new development. See the [Json.NET](http://james.newtonking.com/json) library for a great alternative that serializes dates using ISO-8601. – Roy Tinker Oct 18 '13 at 22:10
  • Has the "one day behind" issue in the case of whole dates (which this certainly was) https://stackoverflow.com/a/56401104/852208 – b_levitt May 31 '19 at 20:29
  • 1
    Woah, careful with the recommendations of Json.NET, it's the defacto json library, yes, but it has 'gotcha' behaviors when serlializing date strings YOU'VE BEEN WARNED: https://github.com/JamesNK/Newtonsoft.Json/issues/862 – Jacob McKay Apr 27 '21 at 17:12
  • 1
    @JacobMcKay Thanks for bringing that to my attention. Completely agree that James Newton-King's design decision (as described at the link in your comment) is harmful. I've removed my recommendation (note I originally made that recommendation prior to the year 2016). – Roy Tinker Apr 27 '21 at 18:08
  • 1
    @ScottWilleke—ISO 8601 formats support offsets, not timezones. The concept of "timezone" is fairly fluid (*cf* [military timezones](https://en.wikipedia.org/wiki/List_of_military_time_zones) and [IANA representative locations](https://www.iana.org/time-zones), aka "IANA timezones"), offsets aren't. :-) – RobG Oct 22 '21 at 00:08
  • @RobG Thanks for clarifying the language around offset vs timezone. In any case, the point of my comment was that the technique in this answer fails to account for either an offset or a timezone. – Scott Willeke Oct 24 '21 at 00:22
134

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Panos
  • 18,992
  • 6
  • 45
  • 54
  • I think there is something wrong in that line of JS. The last two slashes act as comments. I don't know regexp enough to fix it. – orandov Jul 21 '09 at 19:08
  • 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. – andreialecu Aug 27 '09 at 15:19
  • 154
    @rball, nonsense: `jsonDate = new Date(+jsonDate.replace(/\/Date\((\d+)\)\//, '$1'));` – eyelidlessness Jan 19 '10 at 05: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. – Mark Rogers Feb 25 '10 at 15:43
  • 2pst: Instead of eval — (new Function('return ' + json))() – Ed Gomoliako Mar 29 '10 at 10:39
  • Based on what was suggested I made it this way: /** * Convert a Json datetime to Date object * @param {Object} jsonDateTime For example /Date(1224043200000)/ * @return {Date} return Date object */ Date.prototype.fromJson = function(jsonDateTime) { var date = new Date(parseInt(jsonDateTime.replace(/^\/Date\((\d+)\)\/$/gi, '$1'), 10)); return date; }; – Gad D Lord May 30 '10 at 20:22
  • 14
    @Edy: `new Function` is almost as bad as `eval`: http://dev.opera.com/articles/view/efficient-javascript/?page=2#avoideval – Marcel Korpel Sep 21 '10 at 11:55
  • 1
    @Gad: please don't post code in a comment; just formulate a new answer. – Marcel Korpel Sep 21 '10 at 11:56
  • @Gad: regex replacements are slow. – Roy Tinker Nov 11 '10 at 21:02
  • 6
    @Edy: That is another form of eval, and is just as 'evil'. Parse the string instead (see my answer below) – Roy Tinker Jun 23 '11 at 21:15
  • 1
    There is no security issue with the eval here, since you're only passing in \d+. But this answers seems just as broken as the accepted one as they both ignore timezone information. (Actually, this one appears as though it will fail if timezone information is present.) – BrainSlugs83 Jul 13 '12 at 04:35
  • 3
    @BrainSlugs83: there *is* a security issue. If the string does not match the regex, or has stuff before or after the matched bit (which, after all, is not anchored with ^ and $), arbitrary text can be passed to eval. You could wrap an `if` statement around it, but then you need to be careful that that condition only matches when the replace regex will match, and not more often. This only goes to show that security is tricky. If you just don't use eval, you don't need to think about all these things. Your life will be easier and you will write more secure software. – gpvos Feb 12 '14 at 13:16
  • 5
    For anyone wondering why the `eval` is such a bad idea, try running the code in this answer with `jsonDate = 'alert(\'NerNer\');/Date(1234567890123)/';` – IMSoP May 23 '16 at 09:23
  • The linked library is very limited, e.g. it supports only time zones Pacific|Mountain|Central|Eastern|Atlantic. I would suggest a decent Date library like [Moment.js](https://momentjs.com/docs/), [Luxon](https://moment.github.io/luxon/index.html#/?id=luxon) or [Day.js](https://day.js.org/en/) – Wernfried Domscheit Mar 15 '23 at 06:46
104

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);
James Newton-King
  • 48,174
  • 24
  • 109
  • 130
Jason Jong
  • 4,310
  • 2
  • 25
  • 33
  • 6
    The JavaScript Date constructor can parse the string for you: `new Date("2009-04-12T20:44:55")` – David Hogue Jun 19 '13 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. http://codeofmatt.com/2013/06/07/javascript-date-type-is-horribly-broken/ – DanO Sep 22 '14 at 17:56
  • Sending non-UTC date will sooner or later get you into trouble. – tymtam Jul 17 '16 at 22:59
69

The original example:

/Date(1224043200000)/  

does not reflect the formatting used by WCF when sending dates via WCF REST using the built-in JSON serialization. (at least on .NET 3.5, SP1)

I found the answer here helpful, but a slight edit to the regex is required, as it appears that the timezone GMT offset is being appended onto the number returned (since 1970) in WCF JSON.

In a WCF service I have:

[OperationContract]
[WebInvoke(
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.WrappedRequest
    )]
ApptVisitLinkInfo GetCurrentLinkInfo( int appointmentsId );

ApptVisitLinkInfo is defined simply:

public class ApptVisitLinkInfo {
    string Field1 { get; set; }
    DateTime Field2 { get; set; }
    ...
}

When "Field2" is returned as Json from the service the value is:

/Date(1224043200000-0600)/

Notice the timezone offset included as part of the value.

The modified regex:

/\/Date\((.*?)\)\//gi

It's slightly more eager and grabs everything between the parens, not just the first number. The resulting time sinze 1970, plus timezone offset can all be fed into the eval to get a date object.

The resulting line of JavaScript for the replace is:

replace(/\/Date\((.*?)\)\//gi, "new Date($1)");
Aaron
  • 775
  • 8
  • 13
  • 10
    this is wrong, new Date(1224043200000-0600) will only subtract 600 from the date, in this case 600 miliseconds, not 6 hours as it should. – ariel Apr 26 '11 at 06:47
  • @ariel: Have a look at [Javascript Date from milliseconds *and timezone*](http://stackoverflow.com/q/13614792/1048572) – Bergi Nov 28 '12 at 22:20
  • I think the timezone offset is only included if you have a timezone on the DateTime object in .NET (which is the default behaviour). If your date is in UTC, use DateTime.SpecifyKind(date, DateTimeKind.UTC) and you'll get the proper UTC value when it serializes out, with no offset, which you can then convert back to the user's timezone as needed. If it's in local time, use .ToUniversalTime() and it'll convert to UTC, and have the "Kind" already specified for you. – Jerod Venema Aug 15 '13 at 01:45
  • in javascript -0100 will be a binary string so be carefull! – verbedr Aug 11 '15 at 13:54
65

Don't repeat yourself - automate date conversion using $.parseJSON()

Answers to your post provide manual date conversion to JavaScript dates. I've extended jQuery's $.parseJSON() just a little bit, so it's able to automatically parse dates when you instruct it to. It processes ASP.NET formatted dates (/Date(12348721342)/) as well as ISO formatted dates (2010-01-01T12.34.56.789Z) that are supported by native JSON functions in browsers (and libraries like json2.js).

Anyway. If you don't want to repeat your date conversion code over and over again I suggest you read this blog post and get the code that will make your life a little easier.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
62

Click here to check the Demo

JavaScript/jQuery

var = MyDate_String_Value = "/Date(1224043200000)/"
var value = new Date
            (
                 parseInt(MyDate_String_Value.replace(/(^.*\()|([+-].*$)/g, ''))
            );
var dat = value.getMonth() +
                         1 +
                       "/" +
           value.getDate() +
                       "/" +
       value.getFullYear();

Result - "10/15/2008"

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Just an improvement for the method above. function formatearFecha(fec) { var value = new Date ( parseInt(fec.replace(/(^.*\()|([+-].*$)/g, '')) ); var mes = value.getMonth(); var dia = value.getDate(); var date = dia + "/" + mes + "/" + value.getFullYear(); if (dia < 10) date = date.substr(0, 0) + '0' + dia + date.substr(1); if (mes < 10) date = date.substr(0, 3) + '0' + mes + date.substr(4); return date; } date formatted to ddMMyyyy. Cheers! – Matias Jun 26 '15 at 12:42
62

If you say in JavaScript,

var thedate = new Date(1224043200000);
alert(thedate);

you will see that it's the correct date, and you can use that anywhere in JavaScript code with any framework.

John Boker
  • 82,559
  • 17
  • 97
  • 130
  • 3
    That's what I would have thought too except it ends up being: var thedate = /Date(1224043200000)/; at least for me... – rball Dec 03 '09 at 03:38
  • 2
    Date() and Date(1224043200000) both give the same result in both Chrome and Firefox. Not sure if this worked in old browsers, but this answer doesn't work in browsers now. – James Sep 12 '11 at 19:21
  • @James, Yes it is giving browser current date. :( – vissu Mar 07 '12 at 08:24
  • 9
    You need to write it as "new Date(1224043200000)". – BrainSlugs83 Jul 13 '12 at 04:38
38

Updated

We have an internal UI library that has to cope with both Microsoft's ASP.NET built-in JSON format, like /Date(msecs)/, asked about here originally, and most JSON's date format including JSON.NET's, like 2014-06-22T00:00:00.0. In addition we need to cope with oldIE's inability to cope with anything but 3 decimal places.

We first detect what kind of date we're consuming, parse it into a normal JavaScript Date object, then format that out.

1) Detect Microsoft Date format

// Handling of Microsoft AJAX Dates, formatted like '/Date(01238329348239)/'
function looksLikeMSDate(s) {
    return /^\/Date\(/.test(s);
}

2) Detect ISO date format

var isoDateRegex = /^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(\.\d\d?\d?)?([\+-]\d\d:\d\d|Z)?$/;

function looksLikeIsoDate(s) {
    return isoDateRegex.test(s);
}

3) Parse MS date format:

function parseMSDate(s) {
    // Jump forward past the /Date(, parseInt handles the rest
    return new Date(parseInt(s.substr(6)));
}

4) Parse ISO date format.

We do at least have a way to be sure that we're dealing with standard ISO dates or ISO dates modified to always have three millisecond places (see above), so the code is different depending on the environment.

4a) Parse standard ISO Date format, cope with oldIE's issues:

function parseIsoDate(s) {
    var m = isoDateRegex.exec(s);

    // Is this UTC, offset, or undefined? Treat undefined as UTC.
    if (m.length == 7 ||                // Just the y-m-dTh:m:s, no ms, no tz offset - assume UTC
        (m.length > 7 && (
            !m[7] ||                    // Array came back length 9 with undefined for 7 and 8
            m[7].charAt(0) != '.' ||    // ms portion, no tz offset, or no ms portion, Z
            !m[8] ||                    // ms portion, no tz offset
            m[8] == 'Z'))) {            // ms portion and Z
        // JavaScript's weirdo date handling expects just the months to be 0-based, as in 0-11, not 1-12 - the rest are as you expect in dates.
        var d = new Date(Date.UTC(m[1], m[2]-1, m[3], m[4], m[5], m[6]));
    } else {
        // local
        var d = new Date(m[1], m[2]-1, m[3], m[4], m[5], m[6]);
    }

    return d;
}

4b) Parse ISO format with a fixed three millisecond decimal places - much easier:

function parseIsoDate(s) {
    return new Date(s);
}

5) Format it:

function hasTime(d) {
    return !!(d.getUTCHours() || d.getUTCMinutes() || d.getUTCSeconds());
}

function zeroFill(n) {
    if ((n + '').length == 1)
        return '0' + n;

    return n;
}

function formatDate(d) {
    if (hasTime(d)) {
        var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
        s += ' ' + d.getHours() + ':' + zeroFill(d.getMinutes()) + ':' + zeroFill(d.getSeconds());
    } else {
        var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
    }

    return s;
}

6) Tie it all together:

function parseDate(s) {
    var d;
    if (looksLikeMSDate(s))
        d = parseMSDate(s);
    else if (looksLikeIsoDate(s))
        d = parseIsoDate(s);
    else
        return null;

    return formatDate(d);
}

The below old answer is useful for tying this date formatting into jQuery's own JSON parsing so you get Date objects instead of strings, or if you're still stuck in jQuery <1.5 somehow.

Old Answer

If you're using jQuery 1.4's Ajax function with ASP.NET MVC, you can turn all DateTime properties into Date objects with:

// Once
jQuery.parseJSON = function(d) {return eval('(' + d + ')');};

$.ajax({
    ...
    dataFilter: function(d) {
        return d.replace(/"\\\/(Date\(-?\d+\))\\\/"/g, 'new $1');
    },
    ...
});

In jQuery 1.5 you can avoid overriding the parseJSON method globally by using the converters option in the Ajax call.

http://api.jquery.com/jQuery.ajax/

Unfortunately you have to switch to the older eval route in order to get Dates to parse globally in-place - otherwise you need to convert them on a more case-by-case basis post-parse.

Community
  • 1
  • 1
Chris Moschini
  • 36,764
  • 19
  • 160
  • 190
30

There is no built in date type in JSON. This looks like the number of seconds / milliseconds from some epoch. If you know the epoch you can create the date by adding on the right amount of time.

johnstok
  • 96,212
  • 12
  • 54
  • 76
  • That's incorrect, JSON uses Javascript dates, with added timezone information-- the epoch is the same as the javascript Date class's epoch (for obvious reasons). – BrainSlugs83 Jul 13 '12 at 04:48
  • 3
    @BrainSlug83 - this answer provides a reference for the assertion that JSON doesn't have a built-in date type. If you disagree, please provide an alternative reference. (You're not thinking of a specific framework that has decided on a string format to represent dates are you? That's not part of the JSON standard, indeed it couldn't be because it would make it impossible to include a string that is not supposed to be taken as a date but that happens to have a set of characters that match the date pattern.) – nnnnnn Apr 11 '13 at 11:07
29

I also had to search for a solution to this problem and eventually I came across moment.js which is a nice library that can parse this date format and many more.

var d = moment(yourdatestring)

It saved some headache for me so I thought I'd share it with you. :)
You can find some more info about it here: http://momentjs.com/

Venemo
  • 18,515
  • 13
  • 84
  • 125
24

I ended up adding the "characters into Panos's regular expression to get rid of the ones generated by the Microsoft serializer for when writing objects into an inline script:

So if you have a property in your C# code-behind that's something like

protected string JsonObject { get { return jsSerialiser.Serialize(_myObject); }}

And in your aspx you have

<script type="text/javascript">
    var myObject = '<%= JsonObject %>';
</script>

You'd get something like

var myObject = '{"StartDate":"\/Date(1255131630400)\/"}';

Notice the double quotes.

To get this into a form that eval will correctly deserialize, I used:

myObject = myObject.replace(/"\/Date\((\d+)\)\/"/g, 'new Date($1)');

I use Prototype and to use it I added

String.prototype.evalJSONWithDates = function() {
    var jsonWithDates = this.replace(/"\/Date\((\d+)\)\/"/g, 'new Date($1)');
    return jsonWithDates.evalJSON(true);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris Woodward
  • 141
  • 2
  • 5
23

In jQuery 1.5, as long as you have json2.js to cover for older browsers, you can deserialize all dates coming from Ajax as follows:

(function () {
    var DATE_START = "/Date(";
    var DATE_START_LENGTH = DATE_START.length;

    function isDateString(x) {
        return typeof x === "string" && x.startsWith(DATE_START);
    }

    function deserializeDateString(dateString) {
        var dateOffsetByLocalTime = new Date(parseInt(dateString.substr(DATE_START_LENGTH)));
        var utcDate = new Date(dateOffsetByLocalTime.getTime() - dateOffsetByLocalTime.getTimezoneOffset() * 60 * 1000);
        return utcDate;
    }

    function convertJSONDates(key, value) {
      if (isDateString(value)) {
        return deserializeDateString(value);
      }
      return value;
    }

    window.jQuery.ajaxSetup({
      converters: {
        "text json": function(data) {
          return window.JSON.parse(data, convertJSONDates);
        }
      }
    });
}());

I included logic that assumes you send all dates from the server as UTC (which you should); the consumer then gets a JavaScript Date object that has the proper ticks value to reflect this. That is, calling getUTCHours(), etc. on the date will return the same value as it did on the server, and calling getHours() will return the value in the user's local timezone as determined by their browser.

This does not take into account WCF format with timezone offsets, though that would be relatively easy to add.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Domenic
  • 110,262
  • 41
  • 219
  • 271
21

Using the jQuery UI datepicker - really only makes sense if you're already including jQuery UI:

$.datepicker.formatDate('MM d, yy', new Date(parseInt('/Date(1224043200000)/'.substr(6)))); 

output:

October 15, 2008

David Clarke
  • 12,888
  • 9
  • 86
  • 116
dominic
  • 31
  • 1
  • 2
20

Don't over-think this. Like we've done for decades, pass a numeric offset from the de-facto standard epoch of 1 Jan 1970 midnight GMT/UTC/&c in number of seconds (or milliseconds) since this epoch. JavaScript likes it, Java likes it, C likes it, and the Internet likes it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jé Queue
  • 10,359
  • 13
  • 53
  • 61
  • 2
    And too bad there are more than 20 epochs to choose from. http://en.wikipedia.org/wiki/Epoch_(reference_date) – Jerther Oct 30 '14 at 19:22
  • That's the [nice thing about standards](https://en.wikiquote.org/wiki/Andrew_S._Tanenbaum). – Marc L. Oct 19 '18 at 15:03
19

Everyone of these answers has one thing in common: they all store dates as a single value (usually a string).

Another option is to take advantage of the inherent structure of JSON, and represent a date as list of numbers:

{ "name":"Nick",
  "birthdate":[1968,6,9] }

Of course, you would have to make sure both ends of the conversation agree on the format (year, month, day), and which fields are meant to be dates,... but it has the advantage of completely avoiding the issue of date-to-string conversion. It's all numbers -- no strings at all. Also, using the order: year, month, day also allows proper sorting by date.

Just thinking outside the box here -- a JSON date doesn't have to be stored as a string.

Another bonus to doing it this way is that you can easily (and efficiently) select all records for a given year or month by leveraging the way CouchDB handles queries on array values.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nick Perkins
  • 8,034
  • 7
  • 40
  • 40
  • There _is_ a standard format for dates in JSON, which is the RFC 3339 format. – gnasher729 Mar 08 '16 at 16:34
  • @gnasher, that would be nice, but is not the case. There are no references from RFC 7159 to 3339 or vice versa. There is no _de jure_ standard JSON date format. All that's left are _de facto_ standards, each of which have pros/cons. [That's the nice thing about standards.](https://en.wikiquote.org/wiki/Andrew_S._Tanenbaum) – Marc L. Oct 19 '18 at 17:02
18

Posting in awesome thread:

var d = new Date(parseInt('/Date(1224043200000)/'.slice(6, -2)));
alert('' + (1 + d.getMonth()) + '/' + d.getDate() + '/' + d.getFullYear().toString().slice(-2));
Dan Beam
  • 3,632
  • 2
  • 23
  • 27
  • 1
    Nice idea, but what if a timezone offset is included? Better to use substr(6) in that case instead of slice(6,-2) -- see my answer below. – Roy Tinker Oct 22 '10 at 19:21
17

Just to add another approach here, the "ticks approach" that WCF takes is prone to problems with timezones if you're not extremely careful such as described here and in other places. So I'm now using the ISO 8601 format that both .NET & JavaScript duly support that includes timezone offsets. Below are the details:

In WCF/.NET:

Where CreationDate is a System.DateTime; ToString("o") is using .NET's Round-trip format specifier that generates an ISO 8601-compliant date string

new MyInfo {
    CreationDate = r.CreationDate.ToString("o"),
};

In JavaScript

Just after retrieving the JSON I go fixup the dates to be JavaSript Date objects using the Date constructor which accepts an ISO 8601 date string...

$.getJSON(
    "MyRestService.svc/myinfo",
    function (data) {
        $.each(data.myinfos, function (r) {
            this.CreatedOn = new Date(this.CreationDate);
        });
        // Now each myinfo object in the myinfos collection has a CreatedOn field that is a real JavaScript date (with timezone intact).
       alert(data.myinfos[0].CreationDate.toLocaleString());
    }
)

Once you have a JavaScript date you can use all the convenient and reliable Date methods like toDateString, toLocaleString, etc.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Scott Willeke
  • 8,884
  • 1
  • 40
  • 52
16
var newDate = dateFormat(jsonDate, "mm/dd/yyyy"); 

Is there another option without using the jQuery library?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bilgin Kılıç
  • 8,707
  • 14
  • 41
  • 67
11

This may can also help you.

 function ToJavaScriptDate(value) { //To Parse Date from the Returned Parsed Date
        var pattern = /Date\(([^)]+)\)/;
        var results = pattern.exec(value);
        var dt = new Date(parseFloat(results[1]));
        return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
    }
Ravi Mehta
  • 454
  • 1
  • 8
  • 20
10

Below is a pretty simple solution for parsing JSON dates. Use the below functions as per your requirement. You just need to pass the JSON format Date fetched as a parameter to the functions below:

function JSONDate(dateStr) {
    var m, day;
    jsonDate = dateStr;
    var d = new Date(parseInt(jsonDate.substr(6)));
    m = d.getMonth() + 1;
    if (m < 10)
        m = '0' + m
    if (d.getDate() < 10)
        day = '0' + d.getDate()
    else
        day = d.getDate();
    return (m + '/' + day + '/' + d.getFullYear())
}

function JSONDateWithTime(dateStr) {
    jsonDate = dateStr;
    var d = new Date(parseInt(jsonDate.substr(6)));
    var m, day;
    m = d.getMonth() + 1;
    if (m < 10)
        m = '0' + m
    if (d.getDate() < 10)
        day = '0' + d.getDate()
    else
        day = d.getDate();
    var formattedDate = m + "/" + day + "/" + d.getFullYear();
    var hours = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
    var minutes = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
    var formattedTime = hours + ":" + minutes + ":" + d.getSeconds();
    formattedDate = formattedDate + " " + formattedTime;
    return formattedDate;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Umar Malik
  • 63
  • 4
  • 10
10

You also can use the JavaScript library moment.js, which comes in handy when you plan do deal with different localized formats and perform other operations with dates values:

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

    function (result) {
        $("#AuthMerchId").text(result.AuthorizationMerchantId);
        $("#SttlMerchId").text(result.SettlementMerchantId);
        $("#CreateDate").text(moment(result.AppendDts).format("L"));
        $("#ExpireDate").text(moment(result.ExpiresDts).format("L"));
        $("#LastUpdate").text(moment(result.LastUpdateDts).format("L"));
        $("#LastUpdatedBy").text(result.LastUpdateNt);
        $("#ProcessIn").text(result.ProcessIn);
    }
    );
    return false;
}

Setting up localization is as easy as adding configuration files (you get them at momentjs.com) to your project and configuring the language:

moment.lang('de');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
martinoss
  • 5,268
  • 2
  • 45
  • 53
10

I get the date like this:

"/Date(1276290000000+0300)/"

In some examples the date is in slightly different formats:

"/Date(12762900000000300)/"
"Date(1276290000000-0300)"

etc.

So I came up with the following RegExp:

/\/+Date\(([\d+]+)\)\/+/

and the final code is:

var myDate = new Date(parseInt(jsonWcfDate.replace(/\/+Date\(([\d+-]+)\)\/+/, '$1')));

Hope it helps.

Update: I found this link from Microsoft: How do I Serialize Dates with JSON?

This seems like the one we are all looking for.

Michael Vashchinsky
  • 2,137
  • 1
  • 17
  • 15
  • 1
    Regexp replacements are slow... It's much faster to grab the integer portion using substr(6) and pass it to parseInt() -- see my answer below. – Roy Tinker Oct 22 '10 at 19:25
  • Also have a look at [Javascript Date from milliseconds *and timezone*](http://stackoverflow.com/q/13614792/1048572) – Bergi Nov 28 '12 at 22:23
9

Check up the date ISO standard; kind of like this:

yyyy.MM.ddThh:mm

It becomes 2008.11.20T22:18.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Thomas Hansen
  • 5,523
  • 1
  • 23
  • 28
  • According to JSON Schema, the "date-time" format corresponds to RFC 3339, section 5.6. So you should write "yyyy-MM-ddTHH:mm:ssZ" for dates in GMT, or the Z replaced with a time zone like +hh:mm. – gnasher729 Apr 11 '14 at 15:53
  • The problem is that WCF and other "old" MS JSON serialization doesn't use this format, and that has to be accounted for. – Marc L. Oct 19 '18 at 14:50
9

This is frustrating. My solution was to parse out the "/ and /" from the value generated by ASP.NET's JavaScriptSerializer so that, though JSON may not have a date literal, it still gets interpreted by the browser as a date, which is what all I really want:{"myDate":Date(123456789)}

Custom JavaScriptConverter for DateTime?

I must emphasize the accuracy of Roy Tinker's comment. This is not legal JSON. It's a dirty, dirty hack on the server to remove the issue before it becomes a problem for JavaScript. It will choke a JSON parser. I used it for getting off the ground, but I do not use this any more. However, I still feel the best answer lies with changing how the server formats the date, for example, ISO as mentioned elsewhere.

Community
  • 1
  • 1
StarTrekRedneck
  • 1,957
  • 1
  • 15
  • 15
  • 2
    That's not legal JSON. It will only work when eval'ing with a Javascript interpreter. But if you're using a JSON decoder, it will choke. – Roy Tinker Oct 22 '10 at 19:18
  • 1
    Agreed. And if I were just dealing with this one piece of data, I wouldn't consider it. But if I'm dealing with an object of several dates and other properties, it's easier to eval() the whole thing than pick out the properties one at a time. In the end, the root issue is the lack of a (legal) JSON date. Until that exists, we are left to our creative hacks. – StarTrekRedneck Oct 25 '10 at 18:27
9

TLDR: You cannot reliably convert that date-only value, send a string instead...

...or at least that is how almost all of these answers should start off.

There is a number of conversion issues that are happening here.

This Is a Date Without Time

Something everybody seems to be missing is how many trailing zeros there are in the question - it almost certainly started out as a date without time:

/Date(1224043200000)/

When executing this from a javascript console as a new Date (the basis of many answers)

new Date(1224043200000)

You get:

enter image description here

The original asker was probably in EST and had a pure date (sql) or a DateTime (not DateTimeOffset) with midnight.

In other words, the intention here is that the time portion is meaningless. However, if the browser executes this in the same timezone as the server that generated it doesn't matter and most of the answers work.

Bit By Timezone

But, if you execute the code above on a machine with a different timezone (PST for example):

enter image description here

You'll note that we are now a day behind in this other timezone. This will not be fixed by changing the serializer (which will still include the timezone in the iso format)

The Problem

Date (sql) and DateTime (.net) do not have timezone on them, but as soon as you convert them to something that does (javascript inferred thru json in this case), the default action in .net is to assume the current timezone.

The number that the serialization is creating is milliseconds since Unix epoch or:

(DateTimeOffset.Parse("10/15/2008 00:00:00Z") - DateTimeOffset.Parse("1/1/1970 00:00:00Z")).TotalMilliseconds;

Which is something that new Date() in javascript takes as a parameter. Epoch is from UTC, so now you've got timezone info in there whether you wanted it or not.

Possible solutions:

It might be safer to create a string property on your serialized object that represents the date ONLY - a string with "10/15/2008" is not likely to confuse anybody else with this mess. Though even there you have to be careful on the parsing side: https://stackoverflow.com/a/31732581

However, in the spirit of providing an answer to the question asked, as is:

function adjustToLocalMidnight(serverMidnight){ 
  var serverOffset=-240; //injected from model? <-- DateTimeOffset.Now.Offset.TotalMinutes
  var localOffset=-(new Date()).getTimezoneOffset(); 
  return new Date(date.getTime() + (serverOffset-localOffset) * 60 * 1000)
}

var localMidnightDate = adjustToLocalMidnight(new Date(parseInt(jsonDate.substr(6))));
Farzad Karimi
  • 770
  • 1
  • 12
  • 31
b_levitt
  • 7,059
  • 2
  • 41
  • 56
8

Add the jQuery UI plugin in your page:

function DateFormate(dateConvert) {
    return $.datepicker.formatDate("dd/MM/yyyy", eval('new ' + dateConvert.slice(1, -1)));
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Thulasiram
  • 8,432
  • 8
  • 46
  • 54
8

A late post, but for those who searched this post.

Imagine this:

    [Authorize(Roles = "Administrator")]
    [Authorize(Roles = "Director")]
    [Authorize(Roles = "Human Resources")]
    [HttpGet]
    public ActionResult GetUserData(string UserIdGuidKey)
    {
        if (UserIdGuidKey!= null)
        {
            var guidUserId = new Guid(UserIdGuidKey);
            var memuser = Membership.GetUser(guidUserId);
            var profileuser = Profile.GetUserProfile(memuser.UserName);
            var list = new {
                              UserName = memuser.UserName,
                              Email = memuser.Email ,
                              IsApproved = memuser.IsApproved.ToString() ,
                              IsLockedOut = memuser.IsLockedOut.ToString() ,
                              LastLockoutDate = memuser.LastLockoutDate.ToString() ,
                              CreationDate = memuser.CreationDate.ToString() ,
                              LastLoginDate = memuser.LastLoginDate.ToString() ,
                              LastActivityDate = memuser.LastActivityDate.ToString() ,
                              LastPasswordChangedDate = memuser.LastPasswordChangedDate.ToString() ,
                              IsOnline = memuser.IsOnline.ToString() ,
                              FirstName = profileuser.FirstName ,
                              LastName = profileuser.LastName ,
                              NickName = profileuser.NickName ,
                              BirthDate = profileuser.BirthDate.ToString() ,
            };
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        return Redirect("Index");
    }

As you can see, I'm utilizing C# 3.0's feature for creating the "Auto" Generics. It's a bit lazy, but I like it and it works. Just a note: Profile is a custom class I've created for my web application project.

Ray Linder
  • 129
  • 2
  • 7
  • so everytime you add a new role [Authorize(Roles = "Human Resources")] , you have to compile and deploy? wow.... :) – Alex Nolasco Jun 02 '10 at 14:16
  • 1
    If this is a JSON service then the redirect seems wrong. I'd return a 404 Not Found if the input key is so invalid it can't possibly be found, (and also 404 if it genuinely is not found). When my users are not logged in I return 403 Forbidden. – Richard Corfield Dec 21 '11 at 21:42
  • It's a "reusable" method. For example, if I wanted to get user data from another View, I can get it as long as I supply the Id. However, if the Id isn't supplied, page redirects to a list of users (Index) to select a user. Simple solution needed for the app, just the way my brain cooked it up at that time. – Ray Linder Dec 25 '11 at 09:26
8

What if .NET returns...

return DateTime.Now.ToString("u"); //"2013-09-17 15:18:53Z"

And then in JavaScript...

var x = new Date("2013-09-17 15:18:53Z");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Juan Carlos Puerto
  • 2,632
  • 1
  • 26
  • 22
8

Mootools solution:

new Date(Date(result.AppendDts)).format('%x')

Requires mootools-more. Tested using mootools-1.2.3.1-more on Firefox 3.6.3 and IE 7.0.5730.13

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
Midhat
  • 17,454
  • 22
  • 87
  • 114
8

FYI, for anyone using Python on the server side: datetime.datetime().ctime() returns a string that is natively parsable by "new Date()". That is, if you create a new datetime.datetime instance (such as with datetime.datetime.now), the string can be included in the JSON string, and then that string can be passed as the first argument to the Date constructor. I haven't yet found any exceptions, but I haven't tested it too rigorously, either.

8
var obj = eval('(' + "{Date: \/Date(1278903921551)\/}".replace(/\/Date\((\d+)\)\//gi, "new Date($1)") + ')');
var dateValue = obj["Date"];
axel22
  • 32,045
  • 9
  • 125
  • 137
在路上
  • 31
  • 1
  • 1
7

In the following code. I have

1. Retrieved the timestamp from the date string.

2. And parsed it into Int

3. Finally Created a Date using it.

var dateString = "/Date(1224043200000)/";
var seconds = parseInt(dateString.replace(/\/Date\(([0-9]+)[^+]\//i, "$1"));
var date = new Date(seconds);
console.log(date);
Harun Diluka Heshan
  • 1,155
  • 2
  • 18
  • 30
4

As a side note, KendoUI supports to convert Microsoft JSON date. So, If your project has the reference to "KendoUI", you may simply use

var newDate = kendo.parseDate(jsonDate);
Safeer Hussain
  • 1,230
  • 1
  • 15
  • 27
4

This uses a regular expression, and it works as well:

var date = new Date(parseInt(/^\/Date\((.*?)\)\/$/.exec(jsonDate)[1], 10));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
3

Another regex example you can try using:

var mydate = json.date
var date = new Date(parseInt(mydate.replace(/\/Date\((-?\d+)\)\//, '$1');
mydate = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();

date.getMonth() returns an integer 0 - 11 so we must add 1 to get the right month number wise

Luminous
  • 1,771
  • 2
  • 24
  • 43
3

The simplest way I can suggest is using regex on JS as:

//Only use [0] if you are sure that the string matches the pattern
//Otherwise, verify if 'match' returns something
"/Date(1512488018202)/".match(/\d+/)[0] 
Reuel Ribeiro
  • 1,419
  • 14
  • 23
3

I use this simple function for getting date from Microsoft JSON Date

function getDateValue(dateVal) {
    return new Date(parseInt(dateVal.replace(/\D+/g, '')));
};

replace(/\D+/g, '') will remove all characters other than numbers

parseInt will convert the string to number

Usage

$scope.ReturnDate = getDateValue(result.JSONDateVariable)
Zain Shaikh
  • 6,013
  • 6
  • 41
  • 66
Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150
3

Try this...

function formatJSONDate(jsonDate) {
            var date = jsonDate;
            var parsedDate = new Date(parseInt(date.toString().substring(6)));
            var newDate = new Date(parsedDate);
            var getMonth = newDate.getMonth() + 1;
            var getDay = newDate.getDay();
            var getYear = newDate.getFullYear(); 

            var standardDate = (getMonth<10 ? '0' : '') + getMonth + '/' + (getDay<10 ? '0' : '') + getDay + '/' + getYear;
            return standardDate;
        }

getYear() returns the year - 1900, This has been deprecated for a while now, it's best to use getFullYear()

prtk
  • 56
  • 6
Noor All Safaet
  • 438
  • 6
  • 19
2

It's easy to convert JSON date to a JavaScript Date:

var s = Response.StartDate;     
s = s.replace('/Date(', '');

s = s.replace(')/', '');

var expDate = new Date(parseInt(s));
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
0

If you are using Kotlin then this will solve your problem.

val dataString = "/Date(1586583441106)/"
val date = Date(Long.parseLong(dataString.substring(6, dataString.length - 2)))
suhas sasuke
  • 640
  • 6
  • 7
0

Simply Use Moment.js. It is very easy

var finalDate = moment("/Date(1198908717056)/").format("dddd, MMM Do YYYY, hh:mm:ss a");

//"Saturday, Dec 29th 2007, 12:11:57 pm"


var finalDate2 = moment("/Date(1198908717056)/").format("DD-MMM-YYYY");  //"29-Dec-2007"
Md Shahriar
  • 2,072
  • 22
  • 11
-6

Your JSON should probably be returning an object of some sort (well, a string representation thereof).

"{ myDate : Date(1224043200000) }"

Using jQuery, you can access your data object this way:

$.get(
    "myJSONFile.php",
    function (data) {
        // data.myDate will be a date object.

        // to show in a short date format (eg: dd/mm/yyyy)
        alert (
            data.myDate.getDate() + "/"
            + (data.myDate.getMonth() + 1) + "/"
            + data.myDate.getFullYear()
        ); // alerts: "15/10/2008"
    }
);
nickf
  • 537,072
  • 198
  • 649
  • 721