JavaScript Date Format – How to Format a Date in JS

 In JavaScript, you can format a date using the toLocaleDateString() method or a library like Moment.js. Here are some examples:

Using toLocaleDateString() method:

php
const date = new Date(); const formattedDate = date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }); console.log(formattedDate); // Example: May 1, 2023

In the above example, toLocaleDateString() method takes two arguments, the first argument specifies the locale to be used for formatting and the second argument is an object that specifies the formatting options.

Using Moment.js library: Moment.js is a popular library for working with dates in JavaScript. You can format a date using Moment.js like this:

javascript
const date = new Date(); const formattedDate = moment(date).format('MMM DD, YYYY'); console.log(formattedDate); // Example: May 01, 2023

In the above example, moment() method takes a Date object as its parameter and format() method specifies the format of the date to be displayed. The format string 'MMM DD, YYYY' will display the date in the format of 'Month Day, Year'. You can change the format string to your desired date format.

Post a Comment (0)
Previous Post Next Post