3.7 C
New York
Friday, January 12, 2024

Parse JSON Strings as JavaScript Date Objects


Introduction

As of late, builders are likely to retailer and transmit large quantities of information utilizing JSON, which might additionally embrace dates. With the intention to correctly use them, these strings then must be parsed as JS Date objects. However how can we go about doing that? That is precisely what we’ll be exploring on this Byte.

JSON and Dates in JavaScript

JSON is a light-weight data-interchange format that’s straightforward for people to learn and write and straightforward for machines to parse and generate. It is a frequent information format with numerous makes use of in information storing and transmitting.

Alternatively, the Date object is a datatype constructed into the JavaScript language. Date objects are created with the new Date( ) constructor. Regardless of JavaScript’s many strengths, it has at all times had a little bit of problem with dates and occasions (therefore the numerous datetime libraries, like second and dayjs).

So, what occurs when it is advisable to deal with dates from a JSON string in JavaScript? Properly, the JSON format solely helps a small variety of primary information varieties: objects, arrays, numbers, strings, booleans, and null. JSON doesn’t have a built-in Date sort. As a substitute, dates in JSON are usually represented as strings.

If you have not accomplished this earlier than, it may appear difficult at first, however parsing JSON dates in JavaScript is simple as soon as you know the way to do it.

Methods to Parse JSON Dates in JavaScript

There are a number of methods to parse JSON dates in JavaScript. We’ll discover two strategies: utilizing the Date() constructor and the Date.parse() methodology. On this Byte, we’ll concentrate on utilizing the Date() constructor.

Utilizing the Date() Constructor

The Date() constructor in JavaScript creates a brand new date object with a specified date and time. If you move a string to the Date() constructor, it tries to parse that string right into a date.

Here is a easy instance:

let jsonString = '{"dateOfBirth": "2023-09-26T00:00:00.000Z"}';
let obj = JSON.parse(jsonString);
let date = new Date(obj.dateOfBirth);

console.log(date);
// Output: 2023-09-26T00:00:00.000Z

Right here we first parse the JSON string right into a JavaScript object utilizing the JSON.parse() methodology. Then, we use the Date() constructor to parse the dateOfBirth property right into a JavaScript Date object.

Be aware: The Date() constructor accepts date strings in a number of codecs, together with ISO 8601, which is the format utilized in our instance. ISO 8601 dates are within the format “YYYY-MM-DDTHH:mm:ss.sssZ”, the place “Z” represents Coordinated Common Time (UTC).

Utilizing the Date.parse() Technique

The Date.parse() methodology in JavaScript is one other approach to parse JSON dates. It really works by changing a date string into the variety of milliseconds since January 1, 1970, 00:00:00 UTC. This could then be used to create a brand new date object. On this instance we’ll additionally present find out how to use the JSON.parse methodology to instantly convert the date string to an object utilizing the reviver callback.

let jsonDate = '{"date":"2023-09-26T12:00:00Z"}';
let parsedDate = JSON.parse(jsonDate, perform(key, worth) {
    if (key == 'date') return new Date(Date.parse(worth));
    return worth;
});
console.log(parsedDate.date);  // Outputs: 2023-09-26T12:00:00.000Z

On this code snippet, we use Date.parse() throughout the JSON.parse() methodology. The Date.parse() methodology returns the variety of milliseconds for the reason that Unix Epoch, which we then move to the Date constructor to create a brand new date object.

The Date.parse methodology is useful whenever you wish to convert the date to a Unix timestamp as an middleman, which may be higher for storage and typically for date manipulations as nicely, relying in your use-case.

Dealing with Errors Throughout Parsing

Whereas parsing JSON dates, it’s normal to come across errors as a consequence of incorrect date codecs. To deal with this, we might normally use JavaScript’s built-in strive...catch assertion, however the Date object would not throw errors in these instances, however as an alternative it returns Invalid Date, which we’ll must test for:

let jsonDate = '{"date":"2023-13-01T12:00:00Z"}'; // Invalid month

let parsedDate = JSON.parse(jsonDate, perform(key, worth) {
    if (key == 'date') return new Date(worth);
    return worth;
});

let d = parsedDate.date;
if (d instanceof Date && !isNaN(d)) {
    console.log(d);
} else {
    console.log('Invalid date!');
}

Right here we use the next code to test if our date is legitimate or not:

d instanceof Date && !isNaN(d)

An Invalid Date will return true for d instanceof Date, however since !isNaN(d) will return false, the general assertion turns into false, and thus it isn’t a sound date.

Different Methods to Parse JSON Dates

Whereas the Date() constructor and Date.parse() methodology are probably the most simple methods to parse JSON dates in JavaScript, there are different options obtainable. One such answer is utilizing a 3rd occasion library like Second.js.

let second = require('second');
let jsonDate = '{"date":"2023-09-26T12:00:00Z"}';

let parsedDate = JSON.parse(jsonDate, perform(key, worth) {
    if (key == 'date') return second(worth).toDate();
    return worth;
});

console.log(parsedDate.date);  // Outputs: 2023-09-26T12:00:00.000Z

We use the second() perform from the Second.js library to parse the date string. This method may be notably helpful when coping with advanced date and time codecs, particularly customized codecs that do not adhere to any commonplace.

Be aware: Whereas Second.js is a strong library, it might be overkill when you solely must parse easy date strings. At all times take into account your particular wants earlier than including exterior dependencies to your venture. For instance, the library dayjs is way more light-weight and has an identical syntax as Second, though it could possibly take a bit extra setup to get sure options working.

Conclusion

On this Byte, we have seemed into totally different strategies of parsing JSON dates in JavaScript, together with the Date() constructor, Date.parse() methodology, and even an exterior library like Second.js. We have additionally mentioned find out how to deal with errors that may happen throughout parsing. As at all times, the most effective method relies on your particular wants and the complexity of the date strings you are coping with.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles