How to format a JavaScript date

leora picture leora · Aug 24, 2010 · Viewed 4.2M times · Source

In JavaScript, how can I format a date object to print as 10-Aug-2010?

Answer

ajeet kanojia picture ajeet kanojia · Dec 1, 2015

If you need slightly less control over formatting than the currently accepted answer, Date#toLocaleDateString can be used to create standard locale-specific renderings. The locale and options arguments let applications specify the language whose formatting conventions should be used, and allow some customization of the rendering.

Options key examples:

  1. day:
    The representation of the day.
    Possible values are "numeric", "2-digit".
  2. weekday:
    The representation of the weekday.
    Possible values are "narrow", "short", "long".
  3. year:
    The representation of the year.
    Possible values are "numeric", "2-digit".
  4. month:
    The representation of the month.
    Possible values are "numeric", "2-digit", "narrow", "short", "long".
  5. hour:
    The representation of the hour.
    Possible values are "numeric", "2-digit".
  6. minute: The representation of the minute.
    Possible values are "numeric", "2-digit".
  7. second:
    The representation of the second.
    Possible values are "numeric", 2-digit".

All these keys are optional. You can change the number of options values based on your requirements, and this will also reflect the presence of each date time term.

Note: If you would only like to configure the content options, but still use the current locale, passing null for the first parameter will cause an error. Use undefined instead.

For different languages:

  1. "en-US": For English
  2. "hi-IN": For Hindi
  3. "ja-JP": For Japanese

You can use more language options.

For example

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016

You can also use the toLocaleString() method for the same purpose. The only difference is this function provides the time when you don't pass any options.

// Example
9/17/2016, 1:21:34 PM

References: