How to format a JavaScript date

ID : 213

viewed : 266

Tags : javascriptdatedate-formattingjavascript

Top 5 Answer for How to format a JavaScript date

vote vote


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 


vote vote


For custom-delimited date formats, you have to pull out the date (or time) components from a DateTimeFormat object (which is part of the ECMAScript Internationalization API), and then manually create a string with the delimiters you want.

To do this, you can use DateTimeFormat#formatToParts. You could destructure the array, but that is not ideal, as the array output depends on the locale:

{ // example 1    let f = new Intl.DateTimeFormat('en');    let a = f.formatToParts();    console.log(a); } { // example 2    let f = new Intl.DateTimeFormat('hi');    let a = f.formatToParts();    console.log(a); }

Better would be to map a format array to resultant strings:

function join(t, a, s) {    function format(m) {       let f = new Intl.DateTimeFormat('en', m);       return f.format(t);    }    return; }  let a = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}]; let s = join(new Date, a, '-'); console.log(s);

You can also pull out the parts of a DateTimeFormat one-by-one using DateTimeFormat#format, but note that when using this method, as of March 2020, there is a bug in the ECMAScript implementation when it comes to leading zeros on minutes and seconds (this bug is circumvented by the approach above).

let d = new Date(2010, 7, 5); let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d); let mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d); let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d); console.log(`${da}-${mo}-${ye}`);

When working with dates and times, it is usually worth using a library (eg. moment.js, luxon) because of the many hidden complexities of the field.

Note that the ECMAScript Internationalization API, used in the solutions above is not supported in IE10 (0.03% global browser market share in Feb 2020).

vote vote


Use the date.format library:

var dateFormat = require('dateformat'); var now = new Date(); dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT"); 


Saturday, June 9th, 2007, 5:46:21 PM  

dateformat on npm

vote vote


If you need to quickly format your date using plain JavaScript, use getDate, getMonth + 1, getFullYear, getHours and getMinutes:

var d = new Date();  var datestring = d.getDate()  + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes();  // 16-5-2015 9:50 

Or, if you need it to be padded with zeros:

var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +     d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);  // 16-05-2015 09:50 
vote vote


Well, what I wanted was to convert today's date to a MySQL friendly date string like 2012-06-23, and to use that string as a parameter in one of my queries. The simple solution I've found is this:

var today = new Date().toISOString().slice(0, 10); 

Keep in mind that the above solution does not take into account your timezone offset.

You might consider using this function instead:

function toJSONLocal (date) {     var local = new Date(date);     local.setMinutes(date.getMinutes() - date.getTimezoneOffset());     return local.toJSON().slice(0, 10); } 

This will give you the correct date in case you are executing this code around the start/end of the day.

var date = new Date();  function toLocal(date) {   var local = new Date(date);   local.setMinutes(date.getMinutes() - date.getTimezoneOffset());   return local.toJSON(); }  function toJSONLocal(date) {   var local = new Date(date);   local.setMinutes(date.getMinutes() - date.getTimezoneOffset());   return local.toJSON().slice(0, 10); }  // check out your devtools console console.log(date.toJSON()); console.log(date.toISOString()); console.log(toLocal(date));  console.log(toJSONLocal(date));

Top 3 video Explaining How to format a JavaScript date