This article shows you a couple of different approaches to converting a given string into a date object in JavaScript.
What strings can be converted to date objects?
First of all, it’s important to note that not all string formats can be converted to date objects in JavaScript. If a string is not in a recognized format, attempting to convert it to a date object may result in an invalid date or an error.
The table below lists valid string formats that are convertible to date objects (proper date strings):
Format | Example |
---|---|
ISO 8601 | “2023-02-28T13:30:00.000Z” |
Short date | “02/28/2023” |
Long date | "February 28, 2023" |
RFC 2822 | “Mon, 28 Feb 2023 13:30:00 GMT” |
Unix timestamp in seconds | “1646079000” |
These string formats can be used with various methods for converting a string to a date in JavaScript, including the Date() constructor and the Date.parse() method. Let’s examine a few practical examples for more clarity.
Using the Date() constructor
Example:
const dateString = '2023-02-28T13:30:00.000Z';
const date = new Date(dateString);
console.log(
'Year: ' + date.getFullYear(),
'Month: ' + date.getMonth(),
'Day: ' + date.getDate()
);
Output:
Year: 2023 Month: 1 Day: 28
If the date string is in the wrong format, you will get an Invalid Date object:
const dateString = '2023-02-282';
const date = new Date(dateString);
console.log(date);
Output:
Invalid Date
Using the Date.parse() method
The Date.parse() method is another way to convert a string to a date in JavaScript. It takes a string as its argument and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. You can use this number to create a new date object.
Example:
const dateString = '2023-02-28T13:30:00.000Z';
const milliseconds = Date.parse(dateString);
const date = new Date(milliseconds);
console.log(
'Year: ' + date.getFullYear(),
'Month: ' + date.getMonth(),
'Day: ' + date.getDate()
);
Output:
Year: 2023 Month: 1 Day: 28
That’s it. Happy coding!