DEV Community

Cover image for How to Convert String to Date in JavaScript
Raja MSR
Raja MSR

Posted on • Originally published at rajamsr.com

How to Convert String to Date in JavaScript

Have you ever encountered a situation where you need to convert a string to date in JavaScript? Sometimes you need to work with dates and times on your website.

But what if you only have a string, like “2024–03–09” or “March 9, 2024”? How can you turn it into a Date object that you can use and change? This is not easy to do in JavaScript. There is no built-in function for this. You can try the Date constructor, but it might not work well. You can also use other libraries, but they might make your code bigger and harder.

In this blog post, I will show you:

  • How to make a date from a string with Intl.DateTimeFormat()
  • Use the Date constructor to turn a string into a date
  • Another way to get a date from a string is Date.parse()
  • Moment.js is a library that can help with string-to-date conversion
  • Compare the advantages and disadvantages of each method

1. Convert string to Date using Intl.DateTimeFormat() method

If you want to format or parse dates and times in different languages, use the Intl.DateTimeFormat() method. It lets you customize how the date and time look. It will return based on the locale and the format you choose. To convert a date string into a Date object with Intl.DateTimeFormat(), follow these steps:

  • Pick a locale and options. They tell how to show the date and time parts.
  • Use format() on a new Intl.DateTimeFormat object. Give it the date string. It will make a new string that matches the locale and options.
  • Use resolvedOptions() on the Intl.DateTimeFormat object. It will give an object with the final properties of the locale and options. It will have the date and time parts, the time zone, the calendar, and the numbering system.
  • Make a new Date object with the date and time parts from the resolvedOptions object. Use Date.UTC() to change the parts to a UTC timestamp. Then give it to the Date constructor.
// The date string to convert
const dateString = "2024-02-26T01:00:00Z";
// Convert the date string to a Date object
const dateObject = new Date(Date.parse(dateString));
// The locale and options for the Intl.DateTimeFormat object
const options = {
  year: "numeric",
  month: "long",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  fractionalSecondDigits: 2,
  timeZone: "UTC"
};
// Create a new Intl.DateTimeFormat() object with the locale and options
const formatter = new Intl.DateTimeFormat("en-US", options);
// Format the date object using the formatter
const formattedString = formatter.format(dateObject);
console.log(formattedString);
// "February 26, 2024, 1:00:00.00 AM"
Enter fullscreen mode Exit fullscreen mode

2. Convert String to Date using the Date constructor

Do you want to learn how to turn a string into a date in JavaScript? You just need to use the Date constructor. This is a special function that takes a string with a valid date format and gives you back a JavaScript Date object. Let me show you an example:

let date = new Date("2024-02-26");
console.log(date); 
// Tue Feb 26 2024 00:00:00 GMT+0000 (Greenwich Mean Time)
Enter fullscreen mode Exit fullscreen mode

JavaScript Date Constructor with Different Parameters<br>

Different formats for the date string are possible, such as ISO 8601, RFC 2822, or a custom format. ISO 8601 date format is recommended because it is clear and consistent.

JavaScript Date ISO 8601 Format<br>

It has this format:

YYYY-MM-DDTHH:mm:ss.sssZ
Enter fullscreen mode Exit fullscreen mode

Where:

  • YYYY is the four-digit year
  • MM is the two-digit month (01–12)
  • DD is the two-digit day (01–31)
  • T is the separator between the date and time
  • HH is the two-digit hour (00–23)
  • mm is the two-digit minute (00–59)
  • ss is the two-digit second (00–59)
  • sss is the optional three-digit millisecond (000–999)
  • Z is the optional time zone offset (+HH:mm or -HH:mm)

For example:

let date = new Date("2024-02-26T03:35:46Z");
console.log(date); 
// Mon Feb 26 2024 09:05:46 GMT+0530 (India Standard Time)
Enter fullscreen mode Exit fullscreen mode

Imagine you’re reading a date string on a website, but you don’t know what time zone it belongs to. It could be very confusing, right? You might think the event is happening at a different time than it is. That’s why it’s important to always include the time zone offset or use UTC when writing date strings. This way, you can avoid any misunderstandings and make sure everyone is on the same page.

JavaScript Time Zones Offset<br>

3. Convert String to Date using using the Date.parse() method

Did you know you can turn a string into a date in JavaScript? It’s easy with the Date.parse() method! Just give it a date string that follows the rules, and it will give you back a magic number. This number is how many milliseconds have passed since the start of 1970 in UTC. Then you can use this number to make a new Date object with the new Date() constructor. How cool is that?

Here is an example of converting string to date using Date.parse() method:

let milliseconds = Date.parse("2024-02-26");
console.log(milliseconds); 
// Output: 1708905600000
let date = new Date(milliseconds);
console.log(date); 
// Output: Mon Feb 26 2024 05:30:00 GMT+0530 (India Standard Time)
Enter fullscreen mode Exit fullscreen mode

JavaScript Date.parse() Method<br>

The Date.parse() method can take the same formats as the Date constructor, but it is smarter and more careful. It can tell if the date string is valid or not and if not, it will return NaN (Not a Number). Here’s an example:

let milliseconds = Date.parse("2024-02-32");
console.log(milliseconds); // NaN
let date = new Date(milliseconds);
console.log(date); 
// Invalid Date
Enter fullscreen mode Exit fullscreen mode

Therefore, it is recommended to always validate the date string before passing it to the Date.parse() method.

4. String-to-date conversion using a library Moment.js

A library like Moment.js can help you convert strings to dates in JavaScript. Moment.js simplifies and standardizes date and time operations. You can add it to your HTML file or use a package manager like npm or yarn to install it.

The moment() function converts strings to dates with Moment.js. It accepts a date string and an optional format string. It returns a Moment object, which is a Date object with extra methods and features. For example:

let date = moment("2024-02-26", "YYYY-MM-DD");
console.log(date); // Moment<2024-02-26T00:00:00+00:00>
Enter fullscreen mode Exit fullscreen mode

Moment.js helps us parse date strings in different formats. You can tell Moment.js what format to use by giving it a format string. Without a format string, Moment.js will try to figure out the format by itself. But this can be wrong or change over time. So you should always use a format string or the ISO 8601 format.

You can turn a Moment object into a Date object with the toDate() method. For example:

let date = moment("2024-02-26", "YYYY-MM-DD").toDate();
console.log(date); 
// Tue Feb 26 2024 00:00:00 GMT+0000 (Greenwich Mean Time)
Enter fullscreen mode Exit fullscreen mode

To learn more about Moment.js, please visit their official website.

Comparison

Here is the comparison of the pros and cons of each method that we discussed in this post:

JavaScript String to Date Conversion Methods — Comparison<br>

Conclusion

In this blog post, you have learned three ways to convert string to date in JavaScript:

  • Convert date string with Intl.DateTimeFormat()
  • Using the Date constructor
  • Using the Date.parse method
  • Using a library like Moment.js

Each way has its advantages and disadvantages, and the choice depends on the use case and preference. However, the general best practices are to use the ISO 8601 format, specify the time zone offset, and validate the date string before parsing.


I hope you found this blog post helpful and informative. If you have any questions or feedback, please comment below.

Website | X/Twitter | LinkedIn

Top comments (0)