Parse a string to a Date object in JavaScript
This post will discuss how to parse a string to a Date object in JavaScript.
There are several ways to parse a string to a Date object in JavaScript, depending on the format of the string and the desired output of the date. Here are some of the most common functions:
1. Using Date() constructor
One way is to use the Date() constructor, which creates a new Date object from a string argument. The string argument should be in a format that is recognized by the Date.parse() function, such as ISO 8601 (YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS), RFC 2822 (Sat, 20 Jun 2020 12:30:00 GMT), or a custom format (MM/DD/YYYY HH:mm:ss). For example, we can convert a string to a date using the Date() constructor like this:
|
1 2 3 4 5 6 7 |
var date1 = new Date("2020-06-21T12:05:20Z"); // ISO format var date2 = new Date("Sun, 21 Jun 2020 12:05:20 GMT"); // RFC format var date3 = new Date("06/21/2020 12:05:20"); // Custom format console.log(date1); // 2020-06-21T12:05:20.000Z console.log(date2); // 2020-06-21T12:05:20.000Z console.log(date3); // 2020-06-21T12:05:20.000Z |
2. Using a custom function
Another option is to use a custom function, which is a user-defined block of code that performs a specific task. We can write our own function to convert a string to a date by using any logic or technique that suits our needs. For example, we can convert it to a date using a custom function like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
var str = "21/06/2020"; function parseDate(str) { // split the string by "/" var parts = str.split("/"); // get the day part var day = parseInt(parts[0]); // get the month part and subtract 1 var month = parseInt(parts[1]) - 1; // get the year part var year = parseInt(parts[2]); // return a new Date object return new Date(year, month, day); } var date = parseDate(str); // 2020-06-20T18:30:00.000Z console.log(date); |
This function is useful if we want more control and flexibility over how to convert strings to dates. However, it may require more code and complexity than the Date() constructor approach.
That’s all about parsing a string to a Date object in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)