How to Parse JSON to Receive a Date Object in JavaScript

How to parse JSON to receive a Date object in JavaScript?

There is no standard JSON representation of dates. You should do what @jAndy suggested and not serialize a DateTime at all; just send an RFC 1123 date string ToString("r") or a seconds-from-Unix-epoch number, or something else that you can use in the JavaScript to construct a Date.

How to parse JSON format date string into date format

If there is no issue in adding a dependency, then you can add moment.js and it will help you to format data in any format
I am supposing that date from server is in this format '/Date(725828400000)/'

var d = item.EMP_DOB;
result.push(moment(Number(d.match(/\d+/)[0])).format('MM/DD/YYYY'));

If you are unable to add moment js then you can do soemthing like

var date = new Date(Number(d.match(/\d+/)[0]));
var day = date.getDate();
day = day = (day < 10) ? ("0" + day) : day;
var month = date.getMonth() + 1);
month = (month < 10) ? ("0" + month) : month;
var dateStr = day + "-" + month + "-" + date.getFullYear();
result.push(dateStr);

Javascript JSON Date Deserialization

I took @LastCoder advice and wrote a simple implementation. It seems to be doing what I wanted it to.

var jsonDates = {
dtrx2: /\d{4}-\d{2}-\d{2}/,
parse: function(obj){
var parsedObj = JSON.parse(obj);
return this.parseDates(parsedObj);
},
parseDates: function(obj){
// iterate properties
for(pName in obj){

// make sure the property is 'truthy'
if (obj[pName]){
var value = obj[pName];
// determine if the property is an array
if (Array.isArray(value)){
for(var ii = 0; ii < value.length; ii++){
this.parseDates(value[ii]);
}
}
// determine if the property is an object
else if (typeof(value) == "object"){
this.parseDates(value);
}
// determine if the property is a string containing a date
else if (typeof(value) == "string" && this.dtrx2.test(value)){
// parse and replace
obj[pName] = new Date(obj[pName]);
}
}
}

return obj;
}
};

A live example is available on jsbin. A reference is available on gist.

How to get Date object from json Response in typescript

@Gunter is absolutely correct. The only thing I would like to add is actually how to deserialize json object keeping its date properties as dates and not strings (from the referenced post its not that easy to see this approach).

Here is my attempt:

export class Helper
{
public static Deserialize(data: string): any
{
return JSON.parse(data, Helper.ReviveDateTime);
}

private static ReviveDateTime(key: any, value: any): any
{
if (typeof value === 'string')
{
let a = /\/Date\((\d*)\)\//.exec(value);
if (a)
{
return new Date(+a[1]);
}
}

return value;
}
}

You can see this approach for example here: JSON.parse Function in the dateReviver example.

Hope this helps.

Is it possible to parse a JSON date that looks like this?

date = new Date("10/11/2019 07:11:17 AM")
console.log(date.toLocaleString('default', {dateStyle: 'long', month: 'long', day: '2-digit'}));

Converting json results to a date

You need to extract the number from the string, and pass it into the Date constructor:

var x = [{
"id": 1,
"start": "\/Date(1238540400000)\/"
}, {
"id": 2,
"start": "\/Date(1238626800000)\/"
}];

var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);

The parts are:

x[0].start                                - get the string from the JSON
x[0].start.match(/\d+/)[0] - extract the numeric part
x[0].start.match(/\d+/)[0] * 1 - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object

What is the right JSON date format?

JSON itself does not specify how dates should be represented, but JavaScript does.

You should use the format emitted by Date's toJSON method:

2012-04-23T18:25:43.511Z

Here's why:

  1. It's human readable but also succinct

  2. It sorts correctly

  3. It includes fractional seconds, which can help re-establish chronology

  4. It conforms to ISO 8601

  5. ISO 8601 has been well-established internationally for more than a decade

  6. ISO 8601 is endorsed by W3C, RFC3339, and XKCD

That being said, every date library ever written can understand "milliseconds since 1970". So for easy portability, ThiefMaster is right.

Angular 8 way to convert json response with string dates to JS date?

The short answer is no as JSON format does not allow date types. See this: https://www.w3schools.com/JS/js_json_datatypes.asp

I don't think you have any choice other than to transform them into Date objects, and besides, it's relatively trivial given your string date format:

ndate = new Date("1986-05-04T22:59:59.000Z")


Related Topics



Leave a reply



Submit