jquery - yyyy - microsoft json date format

How do I format a Microsoft JSON date? (20)

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:


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) {
    { MismatchId: id },

    function (result) {

  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.


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);
        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 + ')');};

    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.


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.

Click here to check the Demo


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

Result - "10/15/2008"

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

Imagine this:

    [Authorize(Roles = "Administrator")]
    [Authorize(Roles = "Director")]
    [Authorize(Roles = "Human Resources")]
    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.

Add the jQuery UI plugin in your page:

function DateFormate(dateConvert) {
    return $.datepicker.formatDate("dd/MM/yyyy", eval('new ' + dateConvert.slice(1, -1)));

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


It becomes 2008.11.20T22:18.

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.

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.

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.

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/

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 %>';

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);

If you say in JavaScript,

var thedate = new Date(1224043200000);

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

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(";

    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;

      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.

Mootools solution:

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

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

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));

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.

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.

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)))); 


October 15, 2008

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");

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.

var newDate = dateFormat(jsonDate, "mm/dd/yyyy"); 

Is there another option without using the jQuery library?