How to Convert a String to a Date Object in JavaScript

To convert a string to a Date object, call the Date() constructor, passing the string as an argument, i.e., const date = new Date(str).

JavaScript
const str = '2022-06-15'; const date = new Date(str); console.log(date.getFullYear()); // 2022 console.log(date.getDate()); // 15 console.log(date); // 2022-06-15T00:00:00.000Z

If a string is passed, the Date() constructor creates a Date object from the information in the string.

Invalid dates

If the passed string has a wrong or unsupported format, an error will be thrown or an invalid date will be created, depending on the implementation.

JavaScript
const invalidDate = new Date('a'); console.log(invalidDate); // Invalid Date const invalidDate2 = new Date('15/6/2022'); console.log(invalidDate2); // Invalid Date

How to Convert a String with a non-ISO-8601 Format to a Date object

It’s important to make sure that the string you pass to the Date() constructor conforms to the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) for consistent parsing behavior across all browsers. Parsing behavior for other formats depends on the implementation and may not work across all browsers.

To convert a string of a format that is not ISO 8601 and retain consistent parsing behavior, we can get the individual date component values from the string and pass them as numbers to the Date() constructor. For example, we can convert a string with the MM/DD/YY format to a Date object like this:

JavaScript
const str = '06/15/2022'; const [month, day, year] = str.split('/'); console.log(month); // 06 console.log(day); // 15 console.log(year); // 2022 const date = new Date(+year, +month - 1, +day); console.log(date); // May 15, 2022

We split the string with the forward-slash (/) using the String split() method to get the individual values for the month, day, and year. We convert them to numbers with the unary operator (+) and pass them to the Date() constructor.

Note: We subtracted 1 from the month when passing it to the Date() constructor because Date() expects a zero-based month value, i.e. 0 = January, 1 = February, 2 = March, etc.

We can take a similar approach when a time is specified in the string. In the following example, the string we convert has hours, minutes, and seconds specified.

JavaScript
const str = '06-15-2022 09:13:50'; const [dateStr, timeStr] = str.split(' '); console.log(dateStr); // 06-15-2022 console.log(timeStr); // 09:13:50 const [month, day, year] = dateStr.split('-'); const [hours, minutes, seconds] = timeStr.split(':'); console.log(month); // 06 console.log(day); // 15 console.log(year); // 2022 const date = new Date( +year, +month - 1, +day, +hours, +minutes, +seconds ); console.log(date); // 2022-06-15T08:13:50.000Z

First, we had to split the string with a space to use the date and time strings separately.

Unlike in the previous example, this time, the values in the date string were separated with a hyphen (-).

So we used this as the separator when calling split() to obtain the month, day, and year individually.

Similarly, the values in the time string were separated with a colon (:), so this was the separator we used to separate them with the String split() method.

After obtaining each date and time value separately, we converted them to numbers with the unary operator (+) and passed them to the Date() constructor.

How to Convert a Date Object to an ISO 8601 String

If we want to convert a Date object to a string for storage in a file or database, we can store it in the ISO 8601 format, so that we can retrieve and easily convert it back to a Date object with browser-independent parsing behavior without using any third-party libraries.

We can do this with the toISOString() method.

JavaScript
const str = '06-15-2022 09:13:50'; const [dateStr, timeStr] = str.split(' '); console.log(dateStr); // 06-15-2022 console.log(timeStr); // 09:13:50 const [month, day, year] = dateStr.split('-'); const [hours, minutes, seconds] = timeStr.split(':'); console.log(month); // 06 console.log(day); // 15 console.log(year); // 2022 const date = new Date( +year, +month - 1, +day, +hours, +minutes, +seconds ); const isoString = date.toISOString(); console.log(isoString); // 2022-06-15T08:13:50.000Z // Can convert back to Date object with browser-independent parsing const sameDate = new Date(isoString); console.log(sameDate.getDate()); // 15 console.log(sameDate.getMinutes()); // 13

The Date toISOString() method returns a string of the date in the ISO 8601 format according to universal time.

The date-fns parse() Function

We can also use parse() function from the date-fns NPM package to easily convert strings of a wide variety of formats to a Date object. Here we specify that the string is of the MM-dd-yyyy hh:m:ss format so that it can be converted correctly.

JavaScript
import { parse } from 'date-fns'; const str = '06-15-2022 09:13:50'; const date = parse(str, 'MM-dd-yyyy hh:m:ss', new Date()); console.log(date.getHours()); // 9 console.log(date.getDate()); // 15 console.log(date); // 2022-06-15T08:13:50.000Z

Key takeaways

  • To convert a string to a Date object in JavaScript, call the Date() constructor and pass the string as an argument.
  • Invalid date formats will result in an error being thrown or an invalid date being created.
  • For non-ISO-8601 date formats, we can split the string and pass the date components as numbers to the Date() constructor.
  • Use the toISOString() method to convert a Date object to an ISO-8601 string for consistent parsing behavior.
  • The date-fns NPM package provides a parse() function to easily convert strings of various formats to a Date object.


11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *