Wednesday, September 27, 2023
HomeProgrammingParse JSON Strings as JavaScript Date Objects

Parse JSON Strings as JavaScript Date Objects


Introduction

As of late, builders are inclined to retailer and transmit large quantities of information utilizing JSON, which might additionally embrace dates. To be able to correctly use them, these strings then should be parsed as JS Date objects. However how will 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 knowledge format with numerous makes use of in knowledge storing and transmitting.

However, 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 all the time had a little bit of problem with dates and instances (therefore the various datetime libraries, like second and dayjs).

So, what occurs when you might want to deal with dates from a JSON string in JavaScript? Effectively, the JSON format solely helps a small variety of fundamental knowledge sorts: objects, arrays, numbers, strings, booleans, and null. JSON doesn’t have a built-in Date sort. As a substitute, dates in JSON are sometimes represented as strings.

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

Find out how 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 deal with 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. Whenever 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.

Word: 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 option 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 will then be used to create a brand new date object. On this instance we’ll additionally present how you can 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, operate(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 while you need 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 resulting from 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 circumstances, 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, operate(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’s not a legitimate date.

Different Methods to Parse JSON Dates

Whereas the Date() constructor and Date.parse() methodology are essentially the most simple methods to parse JSON dates in JavaScript, there are various options out there. One such answer is utilizing a 3rd get together library like Second.js.

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

let parsedDate = JSON.parse(jsonDate, operate(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() operate from the Second.js library to parse the date string. This strategy may be notably helpful when coping with complicated date and time codecs, particularly customized codecs that do not adhere to any normal.

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

Conclusion

On this Byte, we have seemed into completely 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 how you can deal with errors that may happen throughout parsing. As all the time, the very best strategy is dependent upon your particular wants and the complexity of the date strings you are coping with.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments