Categories
JavaScript Answers

How to Convert a String to a Date Object in JavaScript?

Spread the love

Sometimes, we have a date string that we want to convert to a date object in JavaScript.

In this article, we’ll look at how to convert a date string to a date object in JavaScript.

Extract the Parts of the Date String and Pass Them to the Date Constructor

One way to create a JavaScript date object from a date string is to extract the date parts from the date string and pass them all into the Date constructor.

For instance, we can write:

const [year, month, day] = '2020-04-03'.split('-');
const date = new Date(year, month - 1, day);
console.log(date.toDateString());

We call split on the date string with '-' to split the date string by the dash.

Then we destructure the year , month , and day from the split string array.

Next, we pass all of that into the Date constructor.

We’ve to subtract 1 from month since the month’s value that the Date constructor accepts is from 0 to 11, where 0 is for January and 11 is for December.

Then we get ‘Fri Apr 03 2020’ from the toDateString method.

We can also massage a date into an ISO date string and pass that into the Date constructor.

For instance, we can write:

const st = "26.04.2020";
const pattern = /(d{2}).(d{2}).(d{4})/;
const date = new Date(st.replace(pattern, '$3-$2-$1'));
console.log(date)

We get the parts of the date string with the pattern regex object.

Then we call replace on the st string and move the parts with the $ placeholder.

d extract digits.

The number in the curly braces is the number of digits to extract.

$1 is the first extracted part, which is '26'

$2 is the 2nd extracted part, which is '04'

And $3 is the 3rd extracted part, which is '2020' .

The Date constructor will create a UTC date.

So we get that date in string form is 'Sat Apr 25 2020 17:00:00 GMT-0700 (Pacific Daylight Time)’ .

moment.js

We can pass in a date string into moment.js’ moment function to convert it into an object we can manipulate.

For instance, we can write:

const momentDate = moment("12-25-2020", "MM-DD-YYYY");

to create a moment date object with the date string format specified in the 2nd argument.

We can use the isValid method to check for a valid date:

const isValid = moment("abc").isValid()
console.log(isValid)

isValid should false since 'abc' isn’t a valid date.

And we can convert a moment date object to a native JavaScript Date instance with toDate :

const date = moment("12-25-2020", "MM-DD-YYYY").toDate();
console.log(date)

Conclusion

To convert a date string to a JavaScript date object, we can either extract the parts of the date string ourselves and put it into the Date constructor.

Or we can use a third-party library like moment.js to help us make the job easier.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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