In JavaScript, formatting the date can be accomplished through various methods.
A formatted date is essential when displaying dates on a webpage, or when converting a date to a specific format.
In this tutorial, we will discuss the different ways of formatting the date in JavaScript.
Using the toDateString() Method
The toDateString() method returns a string that represents the date in a human-readable format.
It takes no arguments and returns a string in the format “ddd mmm dd yyyy”. Here’s an example:
const date = new Date(); const formattedDate = date.toDateString(); console.log(formattedDate);
Output: Mon Feb 21 2023
Using the toLocaleDateString() Method
The toLocaleDateString() method returns a string that represents the date in the local date format.
It takes optional arguments for locale and options. Here’s an example:
const date = new Date(); const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; const formattedDate = date.toLocaleDateString('en-US', options); console.log(formattedDate);
Output: Monday, February 21, 2023
Using a Library
Another way to format the date in JavaScript is by using a library like Moment.js.
Moment.js provides many formatting options for dates and times. Here’s an example:
const date = new Date(); const formattedDate = moment(date).format('MMMM Do YYYY, h:mm:ss a'); console.log(formattedDate);
Output: February 21st 2023, 11:59:58 pm
In conclusion, there are different methods to format the date in JavaScript.
Using toDateString() and toLocaleDateString() methods, you can format the date in a human-readable or local format.
Further, you can use a library like Moment.js to format the date in various ways. It’s important to choose the method that best suits your use case.