How to use Intl.DateTimeFormat() and new Date() In Javascript
Using Intl.DateTimeFormat() and new Date(), the approach formats the input string using specified options for year, month, and day. It then creates a new Date object from the formatted string, effectively converting the string into a date.
Example: This example formats “May 1, 2019” into a date string, then converts it back to a Date object using Intl.DateTimeFormat() and new Date().
const dateString = "May 1, 2019";
const options = { year: 'numeric', month: 'long', day: 'numeric' };
// Format the input string
const formattedDate = new Intl.DateTimeFormat('en-US', options).format(
new Date(dateString));
// Create a new Date object from the formatted string
const date = new Date(formattedDate);
console.log(date);
Output
2019-05-01T00:00:00.000Z
Convert string into date using JavaScript
In this article, we will convert a string into a date using JavaScript. A string must follow the pattern so that it can be converted into a date.
A string can be converted into a date in JavaScript through the following ways:
Table of Content
- Using JavaScript Date() constructor
- Using JavaScript toDateString() method
- Using Date.parse() method
- Using Intl.DateTimeFormat() and new Date():