How to Format a Date in JavaScript?
Last Updated :
17 Nov, 2024
Here are different ways to format the date in JavaScript.
1. Using the toDateString() Method
The toDateString() method formats the date object into a human-readable format as Day Month Date Year.
Syntax
dateObj.toDateString();
JavaScript
const date = new Date();
const formatDate = date.toDateString();
console.log(formatDate);
2. Using toISOString() Method
The toISOString() method will format the data into the International Standards following the ISO 8601 format.
Syntax
dateObj.toISOString();
JavaScript
const date = new Date();
const formatDate = date.toISOString();
console.log(formatDate);
Output2024-11-01T09:16:12.793Z
3. Using toLocaleDateString() Method
The toLocaleDateString() method formats the date part of the date object into the same format as acquired by your system or in the specified format.
Syntax
dateObj.toLocaleDateString();
JavaScript
const date = new Date();
const formatLocalDate = date.toLocaleDateString();
const formatSpecified = date.toLocaleDateString("hi-IN");
console.log(formatLocalDate);
console.log(formatSpecified);
Output11/1/2024
1/11/2024
4. Using toLocaleString() Method
The toLocaleString() method will work in the similar way as the toLocaleDateString() works. The only difference is that it also returns the time with the formatted string.
Syntax
dateObj.toLocaleString();
JavaScript
const date = new Date();
const formatLocalDate = date.toLocaleString();
const formatSpecified = date.toLocaleString("hi-IN");
console.log(formatLocalDate);
console.log(formatSpecified);
Output11/1/2024, 9:16:12 AM
1/11/2024, 9:16:12 am
5. Using Intl.DateTimeFormat() Method
The Intl.DateTimeFormat() method is a powerful object method to format the date. It formats the date into specified format and with the specified options for formatting the date and time.
Syntax
const formatObj = new Intl.DateTimeFormat("en-US");
formatObj.format(dateObj);
JavaScript
const date = new Date();
const dateTimeFormatter = new Intl.DateTimeFormat("en-US", {dateStyle: 'long'});
const formatDate = dateTimeFormatter.format(date);
console.log(formatDate);
6. Manually Format Date using Date Methods
In this approach, we will use the different date methods to get the day, date, month and year of the date object and then concat them to form a formatted date string.
JavaScript
const weekDays =
['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const monthsArr =
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const currentDateObj = new Date();
const currentDay = weekDays[currentDateObj.getDay()];
const currentDate = currentDateObj.getDate();
const currentMonth = monthsArr[currentDateObj.getMonth()];
const currentYear = currentDateObj.getFullYear();
console.log(`${currentDay} ${currentDate} ${currentMonth}, ${currentYear}`);