How to Format a JavaScript Date
Topic: JavaScript / jQueryPrev|Next
Answer: Use the toLocaleString() Method
You can simply use the toLocaleString() method to format a date in desired format in JavaScript.
Let's take a look at the following example to understand how it basically works:
Example
Try this code »// Create a date object
var today = new Date();
// Get year, month, and day part from the date
var year = today.toLocaleString("default", { year: "numeric" });
var month = today.toLocaleString("default", { month: "short" });
var day = today.toLocaleString("default", { day: "2-digit" });
// Generate custom date string
var formattedDate = [day, month, year].join("-");
console.log(formattedDate);
To specify options but use the browser's default locale, use "default". Possible values for month property are "numeric", "2-digit", "narrow", "short", "long". Whereas, the possible values for year and day properties are "numeric", and "2-digit".
The following example shows how to format a date string to another format in JavaScript:
Example
Try this code »// Create a date object from a date string
var date = new Date("2021-10-06"); // yyyy-mm-dd
// Get year, month, and day part from the date
var year = date.toLocaleString("default", { year: "numeric" });
var month = date.toLocaleString("default", { month: "short" });
var day = date.toLocaleString("default", { day: "2-digit" });
// Generate custom date string
var formattedDate = day + "-" + month + "-" + year;
console.log(formattedDate); // Prints: 06-Oct-2021
Related FAQ
Here are some more FAQ related to this topic:

