Q:

How to Format a JavaScript Date

0

How to Format a JavaScript Date

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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:

// 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:

// 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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Parse a String to a Date Object in JavaScri... >>
<< How to Convert a String to Boolean in JavaScript...