How to Convert a String to a Date Object in JavaScript

Subscribe to Coding Beauty Newsletter

Gain useful insights and advance your web development knowledge with weekly tips and tutorials from Coding Beauty. Over 2,000 developers subscribe.

1. The Date() Constructor

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). For example:

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. For example:

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:

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.

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.

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.

2. 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.

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


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 *