3

Here is what I am getting as data:

jsonp1290537545248( [{"Active":true,"EndDate":"\/Date(-62135578800000-0500)\/","StartDate":"\/Date(1280635200000-0400)\/"}] );

  $.getJSON(url, {},
      function (data) {
          alert(data[0].EndDate);
          alert(Date(data[0].StartDate));
          //alert(data[0].StartDate.getDate());// + "/" + (data[0].StartDate.getMonth() + 1) + "/" + data[0].StartDate.getFullYear()); // alerts: "15/10/2008" 
          //var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
          alert('dd    ' + new Date(parseInt(data.substr(6)))); 

      });

How do I get in the MM/DD/YYYY format?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nick Kahn
  • 19,652
  • 91
  • 275
  • 406

5 Answers5

5

I would use a similar regex to what Zain posted, but not use eval() like this (demo):

var start = parseInt(data.StartDate.replace(/\/Date\((.*?)[+-]\d+\)\//i,"$1"), 10),
    date = new Date( start ),
    fStart = date.getMonth()+1 + '/' + date.getDate() + '/' + date.getFullYear();

And what is that end date? It doesn't seem to be a difference and if you use that number as a new date you end up with "Sun Dec 31 0000 22:59:59 GMT-0600 (Central Standard Time)"... so I wasn't sure what to do with that value.

Mottie
  • 84,355
  • 30
  • 126
  • 241
  • i try to use the EndDate and i get 1/1/1 here is what i am getting `jsonp1290545857216( [{"Active":true, "EndDate":"\/Date(-62135578800000-0500)\/","StartDate":"\/Date(1280635200000-0400)\/"}]` – Nick Kahn Nov 23 '10 at 20:59
  • does not seems correct and i am getting `Tue Nov 23 2010 16:01:35 GMT-0500 (Eastern Standard Time)` if i do `alert(Date(data[0].StartDate));` and if i use your code and i get `8/1/2010` ??? – Nick Kahn Nov 23 '10 at 21:03
  • 1
    The demo is showing 7/31/2010 for the start date... Maybe because I changed the regex to remove the `-0400` and `-0500` on the end?... I guess isn't really necessary since `parseInt()` ignores it anyway. So, what is the end date supposed to be? – Mottie Nov 23 '10 at 23:05
  • `EndDate` is `null` in my database and `StartDate` in my database is `2010-08-01 00:00:00.000` so its showing `8/1/10` which seems correct. is there a way to show `null` instead of showing `1/1/1` – Nick Kahn Nov 24 '10 at 15:00
  • 1
    I guess you could just check the value of `date.getFullYear()` and if it is less than umm something like 1970 then change `fStart` to `null`. – Mottie Nov 25 '10 at 04:47
  • @Mottie this is super rad! Thank you – Leonardo Wildt Sep 16 '16 at 17:22
4

This might help. See the demo at http://jsfiddle.net/zainshaikh/pysAR/.

var date = eval(data[0].StartDate.replace(/\/Date\((.*?)\)\//gi, "new Date($1)"));

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

How do I format a Microsoft JSON date?

Community
  • 1
  • 1
Zain Shaikh
  • 6,013
  • 6
  • 41
  • 66
  • Zain, have to download the script in order to use the `jsonData.replace` ? – Nick Kahn Nov 23 '10 at 18:53
  • oops, sorry, that was a mistake I corrected. this code will return you the native Date object of javascript. If you want to format it differently, then you would need to download the `Javascript Date Format` script. – Zain Shaikh Nov 23 '10 at 18:55
  • still getting `Date/1280635200000-0400/` as my start date after i implement ur code – Nick Kahn Nov 23 '10 at 18:58
  • Please check again, I have changed a little in the regular expression. also added a link to demo page. – Zain Shaikh Nov 23 '10 at 19:06
4

It's necessary to consider the timezone when determining which date it is. I assume that the first part of the date is the output from Date.getTime() of Java or JavaScript (i.e. the number of milliseconds since January 1, 1970, 00:00:00 UTC).

For the correct output for all times on a date, it is necessary to apply the timezone offset (e.g. -0500 for Eastern Standard Time) before creating the Date object and then use the UTC methods to get parts of the date. The reason is that JavaScript does not provide a Date.setTimezoneOffset() method to set the timezone to the correct one (it's not possible to change it from the visitor's system timezone).

Code example

Here's the code I came up with. It uses a regex to extract the parts of the encoded date, applies the specified timezone offset, creates a Date object, and then builds a date from the parts (demo: http://jsfiddle.net/Wa8LY/1/).

var dateParts = data[0].StartDate.match(/\((.*)([+-])(..)(..)\)/);
var dateObj = new Date(
    /* timestamp in milliseconds */ Number(dateParts[1]) +
    /* sign of timezone offset */ Number(dateParts[2] + '1') *
    /* hours and minutes offset */ (36e5 * dateParts[3] + 6e4 * dateParts[4])
);

var dateMMDDYYYY = [dateObj.getUTCMonth() + 1,
                    dateObj.getUTCDate(),
                    dateObj.getUTCFullYear()].join('/');

Left padding the components

If you need to left pad the components of the date (e.g. 01/01/0001), you could use this function to help do so:

function leftPadWithZeroes(str, len) {
    return (new Array(len + 1).join('0') + str).slice(-len);
}

And change the last lines to (demo: http://jsfiddle.net/5tkpV/1/):

var dateMMDDYYYY = [leftPadWithZeroes(dateObj.getUTCMonth() + 1, 2),
                    leftPadWithZeroes(dateObj.getUTCDate(), 2),
                    leftPadWithZeroes(dateObj.getUTCFullYear(), 4)].join('/');
PleaseStand
  • 31,641
  • 6
  • 68
  • 95
2

Auto convert serialized JSON dates to actual Javascript dates

Since you're using jQuery, you might be interested in the code I've written that auto converts serialized dates to actual Javascript dates.

Your code would still use $.parseJSON() on the client but with the second parameter where you tell it to automatically convert dates. Existing code will still work, because extended functionality only parses dates on your demand.

Check blog post and find out yourself. It's reusable and will work globally so you could just forget about this manual date conversion.

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • I checked the blog post and tried with "/Date(1486944000000)/". I am getting error "Invalid JSON: /Date(1486944000000)/". Do you have any fiddle to show how this test value will work? – LCJ Feb 14 '17 at 23:27
0

The following worked because my datestring was "/Date(1334514600000)\"

'function ConvertJsonDateString(jsonDate) {  
   var shortDate = null;    
   if (jsonDate) {  
       var regex = /-?\d+/;  
       var matches = regex.exec(jsonDate);  
       var dt = new Date(parseInt(matches[0]));  
       var month = dt.getMonth() + 1;  
       var monthString = month > 9 ? month : '0' + month;  
       var day = dt.getDate();  
       var dayString = day > 9 ? day : '0' + day;  
       var year = dt.getFullYear();  
       shortDate = monthString + '/' + dayString + '/' + year;  
}  
return shortDate;  
};'
Amit
  • 559
  • 5
  • 8