How to Convert a String into a Date in JavaScript

The best format for string parsing is the date ISO format with the JavaScript Date object constructor.

But strings are sometimes parsed as UTC and sometimes as local time, which is based on browser vendor and version. It is recommended is to store dates as UTC and make computations as UTC.

To parse a date as UTC, you should append a Z:

new Date('2020-04-10T10:20:30Z');

The "Z" is crucial to ensure that the string is interpreted as UTC, not as local time.

The date objects keep track of a specific instant in time, which is irrespective of timezone. If you use the Date's UTC methods, you will access that instant in UTC. In case you use non-UTC methods, you will access it in local time.

let str = "2020-04-10T17:14:00";
let date = new Date(str + "Z");
console.log("UTC string:  " + date.toUTCString());
console.log("Local string:  " + date.toString());
console.log("Hours local:  " + date.getHours());
console.log("Hours UTC:   " + date.getUTCHours());

Now JavaScript's date and time format is a subset of ISO-8601 format, except that JavaScript's Date always has a time component, while ISO-8601 has the concept that value may only be as specific as it is precise. That is, 2020-04-10 in JavaScript is a specific date and time, but in ISO-8601, it is just the date without time.

Date and Time

You can use the Date object to display the current Date and time, create a calendar, build a timer, etc. The new operator is used to create a date object, and a set of methods become available to operate on the object. It allows you to set and get the year, month, day, hour, minute, second, and millisecond using either local time or UTC time.

Do you find this helpful?

Related articles