By leora


2010-08-23 23:28:26 8 Comments

How can I format a JavaScript date object to print as 10-Aug-2010?

30 comments

@Chris Kobrzak 2019-11-22 16:14:04

In order to format a date as e.g. 10-Aug-2010, you might want to use .toDateString() and ES6 array destructuring.

const formattedDate = new Date().toDateString()
const [, month, day, year] = formattedDate.split(' ')

const ddMmmYyyy = `${day}-${month}-${year}`
// or
const ddMmmYyyy = [day, month, year].join('-')

@K Vij 2019-11-17 03:52:09

As of 2019, it looks like you can get toLocaleDateString to return only certain parts and then you can join them as you wish:

var date = new Date();

console.log(date.toLocaleDateString("en-US", { day: 'numeric' }) 
            + "-"+ date.toLocaleDateString("en-US", { month: 'short' })
            + "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) );

> 16-Nov-2019

console.log(date.toLocaleDateString("en-US", { month: 'long' }) 
            + " " + date.toLocaleDateString("en-US", { day: 'numeric' }) 
            + ", " + date.toLocaleDateString("en-US", { year: 'numeric' }) );

> November 16, 2019

@Alireza 2017-07-19 12:58:53

OK, we have got something called Intl which is very useful for formatting a date in JavaScript these days:

Your date as below:

var date = '10/8/2010';

And you change to Date by using new Date() like below:

date = new Date(date);

And now you can format it any way you like using a list of locales like below:

date = new Intl.DateTimeFormat('en-AU').format(date); // Australian date format: "8/10/2010" 


date = new Intl.DateTimeFormat('en-US').format(date); // USA date format: "10/8/2010" 


date = new Intl.DateTimeFormat('ar-EG').format(date);  // Arabic date format: "٨‏/١٠‏/٢٠١٠"

If you exactly want the format you mentioned above, you can do:

date = new Date(Date.UTC(2010, 7, 10, 0, 0, 0));
var options = {year: "numeric", month: "short", day: "numeric"};
date = new Intl.DateTimeFormat("en-AU", options).format(date).replace(/\s/g, '-');

And the result is going to be:

"10-Aug-2010"

For more see the Intl API and Intl.DateTimeFormat documentation.

@Pants 2019-08-10 12:29:26

Not supported by IE

@Melchia 2019-11-01 13:43:44

You should have a look at DayJs It's a remake of momentJs but lighter.

Fast 2kB alternative to Moment.js with the same modern API

Day.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers with a largely Moment.js-compatible API. If you use Moment.js, you already know how to use Day.js.

var date = Date.now();
const formatedDate = dayjs(date).format("YYYY-MM-DD")
console.log(formatedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.16/dayjs.min.js" crossorigin="anonymous"></script>

@ajeet kanojia 2015-12-01 08:11:09

Use toLocaleDateString()

The toLocaleDateString() method returns a string with a language-sensitive representation of the date portion of the date. The locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function.

The values you can passed in options for different keys:

  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:

@yckart 2016-05-17 05:07:11

I think you mean toLocaleString/toLocaleDateString... The method toDateString doesn't accept any parameters. developer.mozilla.org/de/docs/Web/JavaScript/Reference/…

@LeOn - Han Li 2017-09-29 03:19:02

Was almost about to use moment.js for a simple format. Fortunately did an extra google search and find there is already native API doing this. Saved a external dependency. Awesome!

@Pankaj Phartiyal 2017-11-16 19:42:51

this says its a non standard, but mozzilla doesn't specify that

@Doug Knudsen 2017-12-17 17:08:19

Seems like this answer should be the best "current" answer. Also used the option "hour12: true" to use 12-hour vs 24-hour format. Maybe should be added to your summary list in the answer.

@Dan 2018-01-05 07:18:52

This is the correct modern answer that formats natively and efficiently you leverage the Intl.DateTimeFormat class.

@carinlynchin 2018-03-22 14:38:28

I like how the locale is optional and automatic... is it possible to sort of skip that one and just do the options parameter? I've tried null and "" and it just keeps breaking

@carinlynchin 2018-03-22 14:39:33

NEVERMIND :) just use undefined :)

@Iarwa1n 2018-06-24 08:40:06

I don't get the upvotes on this answer. It does not solve the problem in the question. (i.e. give me a date which looks like 10-Aug-2010). Using toLocaleDateString() that is quite difficult. The date.format library seems to be the better solution (at least for Node users)

@Sandeep Kumar 2018-08-29 22:12:00

timeZoneName option doesn't works in IE (tested in IE 11)

@ironarm 2018-08-30 19:53:04

This solution is cool, but only if locale of the server is the format you want. I.E., if you can't find a language that has the order and delimiter you want, you have to write your own function (or use a library if you're weak). Ex: you could use "en-au" to get hyphens, but it puts the year at the end, you might want it first.

@al.koval 2018-09-04 05:33:06

date1.toLocaleString('en-US').replace(',',''); return this "9/17/2016 1:21:34 PM"

@wbharding 2019-06-22 17:49:47

If passing undefined as the first locale parameter feels arbitrary, you can instead pass the value "default" to utilize the browser's locale settings, per MDN docs developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

@Max Fahl 2019-07-31 06:38:43

I'm surprised that I've missed this one. Well, I guess you learn something new everyday.

@Toni Leigh 2019-08-12 15:15:19

For English, use en-GB, for American English, use en-US - remember that the dates in the UK are day, month, then year so for products targeting both markets there could be confusion

@K Vij 2019-11-27 20:33:14

@Iarwa1n This answer hasn't mentioned but you can use toLocaleDateString to return only certain parts that you can then join as you wish. Check my answer below. date.toLocaleDateString("en-US", { day: 'numeric' }) + "-"+ date.toLocaleDateString("en-US", { month: 'short' }) + "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) should give 16-Nov-2019

@lewdev 2018-10-13 04:19:30

Packaged Solution: Luxon

If you want to use a one solution to fit all, I highly recommend using Luxon (a modernized version of Moment.js) which also does formatting in many locales/languages and tons of other features.

Luxon is hosted on the Moment.js website and developed by a Moment.js developer because Moment.js has limitations that the developer wanted to address but couldn't.

To install:

npm install luxon or yarn add luxon (visit link for other installation methods)

Example:

luxon.DateTime.fromISO('2010-08-10').toFormat('yyyy-LLL-dd');

Yields:

10-Aug-2010

Manual Solution

Using similar formatting as Moment.js, Class DateTimeFormatter (Java), and Class SimpleDateFormat (Java), I implemented a comprehensive solution formatDate(date, patternStr) where the code is easy to read and modify. You can display date, time, AM/PM, etc. See code for more examples.

Example:

formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss:S')

(formatDate is implemented in the code snippet below)

Yields:

Friday, October 12, 2018 18:11:23:445

Try the code out by clicking "Run code snippet."

Date and Time Patterns

yy = 2-digit year; yyyy = full year

M = digit month; MM = 2-digit month; MMM = short month name; MMMM = full month name

EEEE = full weekday name; EEE = short weekday name

d = digit day; dd = 2-digit day

h = hours am/pm; hh = 2-digit hours am/pm; H = hours; HH = 2-digit hours

m = minutes; mm = 2-digit minutes; aaa = AM/PM

s = seconds; ss = 2-digit seconds

S = miliseconds

var monthNames = [
  "January", "February", "March", "April", "May", "June", "July",
  "August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
];
function formatDate(date, patternStr){
    if (!patternStr) {
        patternStr = 'M/d/yyyy';
    }
    var day = date.getDate(),
        month = date.getMonth(),
        year = date.getFullYear(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        miliseconds = date.getMilliseconds(),
        h = hour % 12,
        hh = twoDigitPad(h),
        HH = twoDigitPad(hour),
        mm = twoDigitPad(minute),
        ss = twoDigitPad(second),
        aaa = hour < 12 ? 'AM' : 'PM',
        EEEE = dayOfWeekNames[date.getDay()],
        EEE = EEEE.substr(0, 3),
        dd = twoDigitPad(day),
        M = month + 1,
        MM = twoDigitPad(M),
        MMMM = monthNames[month],
        MMM = MMMM.substr(0, 3),
        yyyy = year + "",
        yy = yyyy.substr(2, 2)
    ;
    // checks to see if month name will be used
    patternStr = patternStr
      .replace('hh', hh).replace('h', h)
      .replace('HH', HH).replace('H', hour)
      .replace('mm', mm).replace('m', minute)
      .replace('ss', ss).replace('s', second)
      .replace('S', miliseconds)
      .replace('dd', dd).replace('d', day)
      
      .replace('EEEE', EEEE).replace('EEE', EEE)
      .replace('yyyy', yyyy)
      .replace('yy', yy)
      .replace('aaa', aaa);
    if (patternStr.indexOf('MMM') > -1) {
        patternStr = patternStr
          .replace('MMMM', MMMM)
          .replace('MMM', MMM);
    }
    else {
        patternStr = patternStr
          .replace('MM', MM)
          .replace('M', M);
    }
    return patternStr;
}
function twoDigitPad(num) {
    return num < 10 ? "0" + num : num;
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(), 'dd-MMM-yyyy')); //OP's request
console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss.S aaa'));
console.log(formatDate(new Date(), 'EEE, MMM d, yyyy HH:mm'));
console.log(formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss.S'));
console.log(formatDate(new Date(), 'M/dd/yyyy h:mmaaa'));

Thank you @Gerry for bringing up Luxon.

@Basil Bourque 2018-10-13 16:40:56

By the way, the troublesome SimpleDateFormat class was supplanted years ago by the java.time.format.DateTimeFormatter class.

@lewdev 2018-10-15 20:34:41

@BasilBourque, noted. They both use the same patterns. I was on a pre-Java8 project for 5 years so I never got exposed to the newer stuff. Thanks!

@Basil Bourque 2018-10-15 20:37:27

See ThreeTen-Backport project for Java 6 & 7, to get most of the java.time functionality with nearly identical API.

@lewdev 2018-10-15 21:07:33

@BasilBourque thanks for the reference, but I don't work on that project anymore but I'll definitely keep this in mind when it comes up.

@Basil Bourque 2018-10-15 21:09:38

Keep in mind that here on Stack Overflow I am speaking to the two million readers of this page, not really you individually. ;-)

@Gerry 2019-04-11 15:34:31

moment is obsolete, use luxon

@Louis Semprini 2019-05-12 20:52:30

manual solution has a bug: .replace('MMMM', MMMM).replace('MMM', MMM).replace('MM', MM).replace('M', M) will replace MMM -> May -> 5ay

@lewdev 2019-05-13 21:42:56

@LouisSemprini Thank you for reporting the bug. I'll fix it when I have time.

@lewdev 2019-05-29 21:17:32

@LouisSemprini I applied a solution, but I wish it could have been more elegant. It won't allow a month name with a month number in the same output, but that would be very unusual.

@Louis Semprini 2019-08-05 18:59:48

@lewdev I had some similar frustrations so I just created a new (non-library-dependent) code snippet that solves all the self-collision problems and has some other nice features like UTC support: stackoverflow.com/a/57364612/1046167

@Louis Semprini 2019-08-05 18:58:17

Here is some ready-to-paste time/date formatting code that does NOT rely on any external modules/libraries or use jQuery or ES7 or anything. Unlike the code in some other answers, this code offers this combo of features:

  • it takes a JavaScript Date object as input
  • it can display date as local time zone or UTC
  • it uses a simple formatting system "{year4} {month02} {second}" that is easy to read and understand even after you write the code, unlike the typical "%D %m %-" which always forces you back to the documentation
  • the formatting system does not have any weird self-collisions like some ad-hoc "DD MM YYYY" systems
  • you can run the test right here and try it

// format_date(date, pattern, utc)
// - date 
//   - a JavaScript Date object
//   - use "new Date()" for current time
// - pattern
//   - a string with embedded {codes} like
//     "{year4}-{month02}-{day02}: {dayname3}"
//     see format_date_funcs below for complete list
//   - any other letters go through unchanged
// - utc
//   - if true, shows date in UTC time "zone"
//   - if false/omitted, shows date in local time zone
//
var month_names = 
[
  "January", "February", "March", "April", "May", "June", "July",
  "August", "September", "October", "November", "December"
];
var day_of_week_names = 
[
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
];
function space_pad2(num)
{
    return num < 10 ? " " + num : num;
}
function zero_pad2(num)
{
    return num < 10 ? "0" + num : num;
}
function space_pad3(num)
{
    if (num < 10) 
        return "  " + num;
    else if (num < 100)
        return " " + num;
    else
        return num;
}
function zero_pad3(num)
{
    if (num < 10) 
        return "00" + num;
    else if (num < 100)
        return "0" + num;
    else
        return num;
}
var format_date_funcs =
{
    // {year4}  = '1902'
    // {year02} =   '02'
    // 
    'year4': function(date, utc)
    {
        var year = utc ? date.getUTCFullYear() : date.getFullYear();
        return year;
    },
    'year02': function(date, utc)
    {
        var year = utc ? date.getUTCFullYear() : date.getFullYear();
        return year.toString().substr(2,2);
    },
    // {month}   =  '1' - '12'
    // {month2}  = ' 1' - '12' (space padded)
    // {month02} = '01' - '12'
    //
    'month': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return            month + 1;
    },
    'month2': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return space_pad2(month + 1);
    },
    'month02': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return zero_pad2(month + 1);
    },
    // {monthname}  = 'January'
    // {monthname3} = 'Jan'
    // 
    'monthname': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return month_names[month];
    },
    'monthname3': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return month_names[month].substr(0, 3);
    },
    // {day}   =  '1' - '31'
    // {day2}  = ' 1' - '31' (space padded)
    // {day02} = '01' - '31'
    // 
    'day': function(date, utc)
    {
        var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
        return date;
    },
    'day2': function(date, utc)
    {
        var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
        return space_pad2(date);
    },
    'day02': function(date, utc)
    {
        var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
        return zero_pad2(date);
    },
    // {dayname}  = 'Tuesday'
    // {dayname3} = 'Tue'
    // 
    'dayname': function(date, utc)
    {
        var day = utc ? date.getUTCDay() : date.getDay(); // [0,6]
        return day_of_week_names[day];
    },
    'dayname3': function(date, utc)
    {
        var day = utc ? date.getUTCDay() : date.getDay(); // [0,6]
        return day_of_week_names[day].substr(0,3);
    },
    // {24hour}   =  '0' - '23'
    // {24hour2}  = ' 0' - '23' (space padded)
    // {24hour02} = '00' - '23'
    //
    '24hour': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return hour;
    },
    '24hour2': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return space_pad2(hour);
    },
    '24hour02': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return zero_pad2(hour);
    },
    // {12hour}   =  '1' - '12'
    // {12hour2}  = ' 1' - '12' (space padded)
    // {12hour02} = '01' - '12'
    // {ampm}     = 'am' or 'pm'
    // {AMPM}     = 'AM' or 'PM'
    //
    '12hour': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        hour = hour % 12; // [0,11]
        if (0 === hour) hour = 12;
        return hour;
    },
    '12hour2': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        hour = hour % 12; // [0,11]
        if (0 === hour) hour = 12;
        return space_pad2(hour);
    },
    '12hour02': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        hour = hour % 12; // [0,11]
        if (0 === hour) hour = 12;
        return zero_pad2(hour);
    },
    'ampm': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return (hour < 12 ? 'am' : 'pm');
    },
    'AMPM': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return (hour < 12 ? 'AM' : 'PM');
    },
    // {minute}   =  '0' - '59'
    // {minute2}  = ' 0' - '59' (space padded)
    // {minute02} = '00' - '59'
    // 
    'minute': function(date, utc)
    {
        var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
        return minute;
    },
    'minute2': function(date, utc)
    {
        var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
        return space_pad2(minute);
    },
    'minute02': function(date, utc)
    {
        var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
        return zero_pad2(minute);
    },
    // {second}   =  '0' - '59'
    // {second2}  = ' 0' - '59' (space padded)
    // {second02} = '00' - '59'
    // 
    'second': function(date, utc)
    {
        var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
        return second;
    },
    'second2': function(date, utc)
    {
        var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
        return space_pad2(second);
    },
    'second02': function(date, utc)
    {
        var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
        return zero_pad2(second);
    },
    // {msec}   =   '0' - '999'
    // {msec3}  = '  0' - '999' (space padded)
    // {msec03} = '000' - '999'
    // 
    'msec': function(date, utc)
    {
        var msec = 
            utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
        return msec;
    },
    'msec3': function(date, utc)
    {
        var msec = 
            utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
        return space_pad3(msec);
    },
    'msec03': function(date, utc)
    {
        var msec = 
            utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
        return zero_pad3(msec);
    },
    // {open} = '{' (in case you actually want '{' in the output)
    //
    'open': function(date, utc)
    {
        return '{';
    }, 
    // {close} = '}' (in case you actually want '}' in the output)
    //
    'close': function(date, utc)
    {
        return '}';
    }, 
};
function format_date(date, pattern, utc)
{
    if (!pattern) 
    {
        pattern = '{month}/{day}/{year4}';
    }

    var ret = '';

    while (pattern.length > 0)
    {
        var s = pattern.indexOf('{');
        var e = pattern.indexOf('}');
        //console.log('s ' + s + ' e ' + e);
        if (-1 !== s && -1 !== e && s < e)
        {
            // - there is a well-formed {foo} in range [s,e]
            // - first we emit range [0,s) as literal
        }
        else
        {
            // - rest of string has no {} or has malformed }{ or { or }
            // - just emit the rest of the string as literal and be done
            s = pattern.length; 
        }
        // emit range [0,s) as literal
        if (s > 0)
        {
            ret += pattern.substr(0, s);
            pattern = pattern.substr(s);
            e -= s;
            s = 0;
        }

        if (0 === pattern.length) break;

        // emit range [s=0,e] by evaluating code
        console.assert(0 === s); // position of {
        console.assert(e > 0);  // position of }
        console.assert('{' === pattern.substr(s, 1));
        console.assert('}' === pattern.substr(e, 1));
        var code = pattern.substr(1,e-1);
        var func = format_date_funcs[code];
        console.assert(func);
        ret += func(date, utc);

        pattern = pattern.substr(e+1);
    }

    return ret;
}

if (1) // test format_date
{
    var fmt = '[';
    for (var func in format_date_funcs) 
    {
        if (!format_date_funcs.hasOwnProperty(func)) continue;
        fmt += '{' + func + '}/';
    }
    fmt += ']';
    var now = new Date();
    console.log(fmt);
    console.log(format_date(now, fmt, false /*utc*/));
    console.log(format_date(now, fmt, true /*utc*/));
}

@simo 2012-06-23 18:49:42

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.

@ChrisV 2014-11-02 12:00:31

Scores on brevity if you can accept ISO date format

@Vajk Hermecz 2015-10-22 22:01:31

You can do new Date(date + " UTC") to trick the timezone, and you can eliminate the setMinutes line. Man, javascript is dirty

@Alex Shaffer 2016-02-25 13:27:26

Y10K compatible version: var today = new Date().toISOString().slice(0,-14) :)

@rofrol 2016-06-02 14:57:58

Or like this new Date().toISOString().split('T')[0]

@rofrol 2016-06-02 15:25:54

Y10K compatible and when browser doesn't returns timezone: new Intl.DateTimeFormat('en-ca-iso8601').format(new Date()) stackoverflow.com/questions/6348431/…

@Gerrie van Wyk 2018-04-25 19:54:53

new Date().toISOString().slice(0, 16).replace('T',' ') to include time

@Steve Bennett 2019-02-07 03:38:19

Just commenting that the lack of timezone is not some minor inconvenience "around the start/end of the day". In Australia, for instance, the date may be wrong until about 11AM - nearly half the day!

@nsandersen 2019-07-25 14:21:28

@slang True, but the lifespan of my program isn't Y10K compatible either :). I'll bank on there being AI to sort this out by then.

@Guilherme Ferreira 2019-04-20 06:29:48

This Module can easily handle mostly every case there is. It is part of a bigger npm package, by Locutus, which includes a variety of functions, but can be used totally independent of the package it self, just copy paste/ adapt a little if not working with npm (change from module to just a function)

As a second parameter it accepts a timestamp, which can come from anywhere, such as Date.getTime()

Also, Locutus maintains a bigger datetime module, also inside the locutus package which will give a more object oriented way to use it

Here you can see other datetime functions, as modules, that proved to be very usefull too.

You can find documentation on parameters and format strings here (note that the doc site is a php site, but the locutus implementation follows exactly the same specs)

Examples of date Module

date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400)//'07:09:40 m is month'

date('F j, Y, g:i a', 1062462400)//'September 2, 2003, 12:26 am'

date('Y W o', 1062462400)//'2003 36 2003'

var $x = date('Y m d', (new Date()).getTime() / 1000) $x = $x + '' var $result = $x.length // 2009 01 09    10

date('W', 1104534000)   //'52'

date('B t', 1104534000) //'999 31'

date('W U', 1293750000.82); // 2010-12-31   '52 1293750000'

date('W', 1293836400); // 2011-01-01    '52'

date('W Y-m-d', 1293974054); // 2011-01-02  '52 2011-01-02'

@site 2019-02-05 19:39:35

To obtain "10-Aug-2010", try:

var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})

For browser support, see toLocaleDateString.

@varun 2019-09-01 17:06:57

I did not need a "-", here is a shorter version with time, date and time zone! date=new Date(); date.toLocaleDateString(undefined, {day:'2-digit', month: 'short', year: 'numeric', hour: 'numeric', minute: 'numeric', timeZoneName: 'short'}); :)

@blairzotron 2019-01-24 15:43:42

A simple function that can return the date, the date + time, or just the time:

var myDate = dateFormatter("2019-01-24 11:33:24", "date-time");
// >> RETURNS "January 24, 2019 11:33:24"

var myDate2 = dateFormatter("2019-01-24 11:33:24", "date");
// >> RETURNS "January 24, 2019"

var myDate3 = dateFormatter("2019-01-24 11:33:24", "time");
// >> RETURNS "11:33:24"


function dateFormatter(strDate, format){
    var theDate = new Date(strDate);
    if (format=="time")
       return getTimeFromDate(theDate);
    else{
       var dateOptions = {year:'numeric', month:'long', day:'numeric'};
       var formattedDate = theDate.toLocaleDateString("en-US", + dateOptions);
       if (format=="date")
           return formattedDate;
       return formattedDate + " " + getTimeFromDate(theDate);
    }
}

function getTimeFromDate(theDate){
    var sec = theDate.getSeconds();
    if (sec<10)
        sec = "0" + sec;
    var min = theDate.getMinutes();
    if (min<10)
        min = "0" + min;
    return theDate.getHours() + ':'+ min + ':' + sec;
}

@onmyway133 2018-11-06 11:54:59

You don't need any libraries. Just extract date components and construct the string. Here is how to get YYYY-MM-DD format. Also note the month index "January is 0, February is 1, and so on."

// @flow

type Components = {
  day: number,
  month: number,
  year: number
}

export default class DateFormatter {
  // YYYY-MM-DD
  static YYYY_MM_DD = (date: Date): string => {
    const components = DateFormatter.format(DateFormatter.components(date))
    return `${components.year}-${components.month}-${components.day}`
  }

  static format = (components: Components) => {
    return {
      day: `${components.day}`.padStart(2, '0'),
      month: `${components.month}`.padStart(2, '0'),
      year: components.year
    }
  }

  static components = (date: Date) => {
    return {
      day: date.getDate(),
      month: date.getMonth() + 1,
      year: date.getFullYear()
    }
  }
}

@Matias Osmerini 2018-08-30 20:04:34

Other way that you can format the date:

function formatDate(dDate,sMode){
    var today = dDate;
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    if(dd<10) {
        dd = '0'+dd
    }
    if(mm<10) {
        mm = '0'+mm
    }
    if (sMode+""==""){
        sMode = "dd/mm/yyyy";
    }
    if (sMode == "yyyy-mm-dd"){
        return  yyyy + "-" + mm + "-" + dd + "";
    }
    if (sMode == "dd/mm/yyyy"){
        return  dd + "/" + mm + "/" + yyyy;
    }
}

@Basj 2018-01-17 20:08:52

This is the main answer modified to have 3-char months, and 2-digit year:

function formatDate(date) {
    var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var day = date.getDate(), monthIndex = date.getMonth(), year = date.getFullYear().toString().substr(-2);
    return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

document.write(formatDate(new Date()));

@Mr Nsubuga 2018-01-08 10:27:33

This may help with the problem:

var d = new Date();

var options = {   
    day: 'numeric',
    month: 'long', 
    year: 'numeric'
};

console.log(d.toLocaleDateString('en-ZA', options));

Date to locate format

@BishopZ 2018-01-27 06:31:57

or d.toLocaleDateString('en-US', options); if you are in the USA.

@Steven Rogers 2019-04-05 19:05:21

This was my solution. Thank you.

@Combine 2017-12-16 18:27:28

I know someone might say that this is silly solution, but it does do the trick by removing the unnecessary information from the date string.

yourDateObject produces:

Wed Dec 13 2017 20:40:40 GMT+0200 (EET)

yourDateObject.toString().slice(0, 15); produces:

Wed Dec 13 2017

@amit77309 2017-11-22 14:24:31

DateFormatter.formatDate(new Date(2010,7,10), 'DD-MMM-YYYY')

=>10-Aug-2010

DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')

=>2017-11-22 19:52:37

DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A')

=>2 02 Wed Wednesday, 2 02 Feb February, 05 2005, 3 03 3 03, 4 04, 5 05, am AM

var DateFormatter = {
  monthNames: [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ],
  dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  formatDate: function (date, format) {
    var self = this;
    format = self.getProperDigits(format, /d+/gi, date.getDate());
    format = self.getProperDigits(format, /M+/g, date.getMonth() + 1);
    format = format.replace(/y+/gi, function (y) {
      var len = y.length;
      var year = date.getFullYear();
      if (len == 2)
        return (year + "").slice(-2);
      else if (len == 4)
        return year;
      return y;
    })
    format = self.getProperDigits(format, /H+/g, date.getHours());
    format = self.getProperDigits(format, /h+/g, self.getHours12(date.getHours()));
    format = self.getProperDigits(format, /m+/g, date.getMinutes());
    format = self.getProperDigits(format, /s+/gi, date.getSeconds());
    format = format.replace(/a/ig, function (a) {
      var amPm = self.getAmPm(date.getHours())
      if (a === 'A')
        return amPm.toUpperCase();
      return amPm;
    })
    format = self.getFullOr3Letters(format, /d+/gi, self.dayNames, date.getDay())
    format = self.getFullOr3Letters(format, /M+/g, self.monthNames, date.getMonth())
    return format;
  },
  getProperDigits: function (format, regex, value) {
    return format.replace(regex, function (m) {
      var length = m.length;
      if (length == 1)
        return value;
      else if (length == 2)
        return ('0' + value).slice(-2);
      return m;
    })
  },
  getHours12: function (hours) {
    // https://stackoverflow.com/questions/10556879/changing-the-1-24-hour-to-1-12-hour-for-the-gethours-method
    return (hours + 24) % 12 || 12;
  },
  getAmPm: function (hours) {
    // https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format
    return hours >= 12 ? 'pm' : 'am';
  },
  getFullOr3Letters: function (format, regex, nameArray, value) {
    return format.replace(regex, function (s) {
      var len = s.length;
      if (len == 3)
        return nameArray[value].substr(0, 3);
      else if (len == 4)
        return nameArray[value];
      return s;
    })
  }
}

console.log(DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss'));
console.log(DateFormatter.formatDate(new Date(), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
console.log(DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));

The format description was taken from Ionic Framework (it does not support Z, UTC Timezone Offset)

Not thoroughly tested

@Prasad DLV 2014-07-21 08:49:51

A JavaScript solution without using any external libraries:

var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)

@Hinrich 2018-05-07 15:00:53

For any one looking for a really simple ES6 solution to copy, paste and adopt:

const dateToString = d => `${d.getFullYear()}-${('00' + (d.getMonth() + 1)).slice(-2)}-${('00' + d.getDate()).slice(-2)}` 

// how to use:
const myDate = new Date(Date.parse('04 Dec 1995 00:12:00 GMT'))
console.log(dateToString(myDate)) // 1995-12-04

@lewdev 2018-10-13 03:56:49

yy = 2-digit year; yyyy = full year

M = digit month; MM = 2-digit month; MMM = short month name; MMMM = full month name

EEEE = full weekday name; EEE = short weekday name

d = digit day; dd = 2-digit day

h = hours; hh = 2-digit hours

m = minutes; mm = 2-digit minutes

s = seconds; ss = 2-digit seconds

S = miliseconds

Used similar formating as Class SimpleDateFormat (Java)

var monthNames = [
  "January", "February", "March", "April", "May", "June", "July",
  "August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
];
function formatDate(date, formatStr){
    if (!formatStr) {
      formatStr = 'dd/mm/yyyy';
    }
    var day = date.getDate(),
        month = date.getMonth(),
        year = date.getFullYear(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        miliseconds = date.getMilliseconds(),
        hh = twoDigitPad(hour),
        mm = twoDigitPad(minute),
        ss = twoDigitPad(second),
        EEEE = dayOfWeekNames[date.getDay()],
        EEE = EEEE.substr(0, 3),
        dd = twoDigitPad(day),
        M = month + 1,
        MM = twoDigitPad(M),
        MMMM = monthNames[month],
        MMM = MMMM.substr(0, 3),
        yyyy = year + "",
        yy = yyyy.substr(2, 2)
    ;
    return formatStr
      .replace('hh', hh).replace('h', hour)
      .replace('mm', mm).replace('m', minute)
      .replace('ss', ss).replace('s', second)
      .replace('S', miliseconds)
      .replace('dd', dd).replace('d', day)
      .replace('MMMM', MMMM).replace('MMM', MMM).replace('MM', MM).replace('M', M)
      .replace('EEEE', EEEE).replace('EEE', EEE)
      .replace('yyyy', yyyy)
      .replace('yy', yy)
    ;
}
function twoDigitPad(num) {
    return num < 10 ? "0" + num : num;
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy hh:mm:ss:S'));
console.log(formatDate(new Date(), 'EEE, MMM d, yyyy hh:mm'));
console.log(formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss:S'));
console.log(formatDate(new Date(), 'yy-MM-dd hh:mm'));

@Marko 2010-08-23 23:35:17

Attention: There are better answers below. This answer was written in 2010 and newer and better solutions have arrived since. The OP should accept another answer.

function formatDate(date) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];

  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

console.log(formatDate(new Date()));  // show current date-time in console

You can edit the array monthNames to use Jan, Feb, Mar, etc..

@Marcel Korpel 2010-08-23 23:41:13

Or extend the Date object, like I did at stackoverflow.com/questions/3187790/…

@Benjamin Oakes 2012-01-17 19:43:13

Really consider using a library like Moment.js or Date.js instead. This problem has been solved many times over.

@Nayan 2014-07-24 15:04:30

Why don't they include a function in Date object to do this?

@Marko 2014-10-31 14:54:28

One important point is that getMonth() method returns a 0 based month index so for example January will return 0 February will return 1, etc...

@mrzmyr 2015-03-30 03:50:09

moment.js 2.9.0 is 11.6k gzipped, this example is 211 bytes gzipped.

@Matt Jensen 2015-09-09 17:27:10

Should be noted that you should never ever, ever, use document.write(). Huge security and performance issues.

@JD Smith 2015-10-14 17:23:10

I can get your requested format in two lines with no libraries: var d = new Date(); var date = d.toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$‌​3');

@Lachlan McD. 2015-11-30 09:57:29

Just a note that date.getMonth() returns 0-11, so you'd want to add 1 if you plan to use that number directly.

@DanceSC 2015-12-28 21:44:23

@TomášZato You claim the answer sucks, yet you have not posted an explanatory comment as to why, is there a reason?

@backdesk 2016-01-28 12:26:46

Just so you know, moment is bloated because it has a lot of locale data. You can easily remove that to get your file size down. In any case mrzmyr is weakly comparing a fully functional date parsing library with the example. There's no comparison imho.

@SergeyB 2016-03-23 21:14:29

Bad answer because: a) wrong solution for the question, produces 10 August 2010 instead of desired 10-Aug-2010 b) reinvents the wheel, as other commenters have suggested momentjs is a good option, c) does not account for locales, making it useless in an internationalized application

@Ben McIntyre 2016-04-27 17:50:06

a library like moment.js (excellent by the way) will be cached after first load most of the time anyway

@dualed 2016-07-21 16:21:34

@BenMcIntyre but it will be at least loaded and executed, possibly also parsed to some object code. There is a in difference in executing 4000 LOC vs. 15

@RobG 2016-09-08 12:41:14

@JDSmith—that requires the output of Date.prototype.toString to be consistent across implementations, which it isn't.

@JD Smith 2016-09-10 03:21:19

@RobG great point! Looks like my regex solution will only work reliably in North America where the major browsers all return the same string format, and would need to be modified elsewhere.

@Patrick Ferreira 2016-10-17 12:45:05

@ajeet kanojia answer is much more portable because it don't needs to write your own translations for "basic" month translations. Obviously, for some "custom" output, your solution would be the good one.

@aero 2017-03-08 16:00:58

Great answers as, sometimes, using other libraries (like moment.js - which is great) add too much overhead. If you need to format 100 dates, say, for a calendar app, you will probably recognize a home rolled solution could be seconds faster than using a 3rd party library.

@trenthogan 2017-04-04 04:47:41

If you are looking for a smaller library you could try github.com/taylorhakes/fecha Coming in at 2.1kb gzipped it says :)

@jinglesthula 2017-07-25 16:20:23

@Nayan my guess - because time is non-trivial, and to attempt to cover all the nuances in an ECMAScript spec that are addressed by libs like moment is probably unworkable

@Jay 2017-08-03 15:36:56

"weakly comparing a fully functional date parsing library with the example. There's no comparison" But if all you need is one function, then that's the comparison that matters. That's like saying that it's foolish to use a car rather than a commercial jetliner, because the airplane can carry many more people and travels much faster. But if what I want to do is transport 1 person 5 miles, the car is the much more practical choice.

@Dylan Hogg 2017-09-30 12:43:07

Super small and useful function. For easy copy paste here are short month names: var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

@Agustín Lado 2017-10-24 15:41:35

I understand not using moment.js for this, but doing it by hand will mean re-implementation when a different format is desired. Use a small tool, like date-fns. If you really care about file size using more modern JS you can import just the format function, which will solve every issue.

@Dr_Derp 2018-09-26 17:26:50

Some people are writing JS without modules (I know, shocking), so having a pure vanilla JS solution is very useful.

@Sung Cho 2018-11-14 23:45:35

I don't think we should encourage people to use libraries such as moment.js for simple requirements like this one. Very rarely the performance overhead + bundle size are justified.

@SuperUberDuper 2019-04-16 15:34:25

Can we realistically avoid moment and luxon these days?

@vdegenne 2017-08-28 12:49:40

Using an ECMAScript Edition 6 (ES6/ES2015) string template:

let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;

If you need to change the delimiters:

const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);

@Kirk Strobeck 2018-01-15 02:33:26

new Date().toLocaleDateString()

// "3/21/2018"

More documentation at developer.mozilla.org

@Eugene Fidelin 2018-02-14 15:39:13

Should be noted that you should never ever, ever, use document.write(). Huge security and performance issues

@Adrian Maire 2017-04-12 09:09:53

Custom formatting function:

For fixed formats, a simple function make the job. The following example generates the international format YYYY-MM-DD:

function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1; //Month from 0 to 11
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

console.log(dateToYMD(new Date(2017,10,5))); // Nov 5

The OP format may be generated like:

function dateToYMD(date) {
    var strArray=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var d = date.getDate();
    var m = strArray[date.getMonth()];
    var y = date.getFullYear();
    return '' + (d <= 9 ? '0' + d : d) + '-' + m + '-' + y;
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5

Note: It is, however, usually not a good idea to extend the JavaScript standard libraries (e.g. by adding this function to the prototype of Date).

A more advanced function could generate configurable output based on a format parameter.

If to write a formatting function is too long, there are plenty of libraries around which does it. Some other answers already enumerate them. But increasing dependencies also has it counter-part.

Standard ECMAScript formatting functions:

Since more recent versions of ECMAScript, the Date class has some specific formatting functions:

toDateString: Implementation dependent, show only the date.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.todatestring

new Date().toDateString(); // e.g. "Fri Nov 11 2016"

toISOString: Show ISO 8601 date and time.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.toisostring

new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"

toJSON: Stringifier for JSON.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tojson

new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"

toLocaleDateString: Implementation dependent, a date in locale format.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaledatestring

new Date().toLocaleDateString(); // e.g. "21/11/2016"

toLocaleString: Implementation dependent, a date&time in locale format.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocalestring

new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"

toLocaleTimeString: Implementation dependent, a time in locale format.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaletimestring

new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"

toString: Generic toString for Date.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tostring

new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"

Note: it is possible to generate custom output out of those formatting >

new Date().toISOString().slice(0,10); //return YYYY-MM-DD

Examples snippets:

console.log("1) "+  new Date().toDateString());
console.log("2) "+  new Date().toISOString());
console.log("3) "+  new Date().toJSON());
console.log("4) "+  new Date().toLocaleDateString());
console.log("5) "+  new Date().toLocaleString());
console.log("6) "+  new Date().toLocaleTimeString());
console.log("7) "+  new Date().toString());
console.log("8) "+  new Date().toISOString().slice(0,10));

@daCoda 2019-01-30 01:08:16

Thanks for the last one.. Useful for setting the date value of HTML Date inputs.

@Aarvy 2019-07-02 07:17:33

new Date().toLocaleDateString() gives you mm/dd/yyyy not dd/mm/yyyy please correct that one.

@Adrian Maire 2019-07-10 11:09:53

@RajanVerma: toLocaleDateString provides your locale, which is probably mm/dd/yyyy because you are in USA. Here, the locale for date is dd/mm/yyyy (that is exactly the point of "locale"). I wrote "e.g." because it is not the specification, but an example of output.

@Iman Bahrampour 2017-10-13 10:58:32

A useful and flexible way for formatting the DateTimes in JavaScript is Intl.DateTimeFormat:

var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));

Result Is: "12-Oct-2017"

The date and time formats can be customized using the options argument.

The Intl.DateTimeFormat object is a constructor for objects that enable language sensitive date and time formatting.

Syntax

new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])

Parameters

locales

Optional. A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the Intl page. The following Unicode extension keys are allowed:

nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".

Options

Optional. An object with some or all of the following properties:

localeMatcher

The locale matching algorithm to use. Possible values are "lookup" and "best fit"; the default is "best fit". For information about this option, see the Intl page.

timeZone

The time zone to use. The only value implementations must recognize is "UTC"; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as "Asia/Shanghai", "Asia/Kolkata", "America/New_York".

hour12

Whether to use 12-hour time (as opposed to 24-hour time). Possible values are true and false; the default is locale dependent.

formatMatcher

The format matching algorithm to use. Possible values are "basic" and "best fit"; the default is "best fit". See the following paragraphs for information about the use of this property.

The following properties describe the date-time components to use in formatted output and their desired representations. Implementations are required to support at least the following subsets:

weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute

Implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. Two algorithms are available for this negotiation and selected by the formatMatcher property: A fully specified "basic" algorithm and an implementation dependent "best fit" algorithm.

weekday

The representation of the weekday. Possible values are "narrow", "short", "long".

era

The representation of the era. Possible values are "narrow", "short", "long".

year

The representation of the year. Possible values are "numeric", "2-digit".

month

The representation of the month. Possible values are "numeric", "2-digit", "narrow", "short", "long".

day

The representation of the day. Possible values are "numeric", "2-digit".

hour

The representation of the hour. Possible values are "numeric", "2-digit".

minute

The representation of the minute. Possible values are "numeric", "2-digit".

second

The representation of the second. Possible values are "numeric", "2-digit".

timeZoneName

The representation of the time zone name. Possible values are "short", "long". The default value for each date-time component property is undefined, but if all component properties are undefined, then the year, month and day are assumed to be "numeric".

Check Online

More Details

@Agi Hammerthief 2017-10-27 08:43:39

The following code will allow you to format the date to either DD-MM-YYYY (27-12-2017) or DD MMM YYYY (27 Dec 2017) :

/** Pad number to fit into nearest power of 10 */
function padNumber(number, prependChar, count) {
  var out = '' + number; var i;
  if (number < Math.pow(10, count))
    while (out.length < ('' + Math.pow(10, count)).length) out = prependChar + out;

  return out;
}

/* Format the date to 'DD-MM-YYYY' or 'DD MMM YYYY' */
function dateToDMY(date, useNumbersOnly) {
  var months = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 
    'Nov', 'Dec'
  ];

  return '' + padNumber(date.getDate(), '0', 1) + 
   (useNumbersOnly? '-' + padNumber(date.getMonth() + 1, '0', 1) + '-' : ' ' + months[date.getMonth()] + ' ')
    + date.getFullYear();
}

Change the order of date.getFullYear() and padNumber(date.getDate(), '0', 1) to make a dateToYMD() function.

See repl.it example for details.

@John Slegers 2016-01-24 21:09:12

In modern browsers (*), you can just do this:

var today = new Date().toLocaleDateString('en-GB', {
    day : 'numeric',
    month : 'short',
    year : 'numeric'
}).split(' ').join('-');

Output if executed today (january 24ᵗʰ, 2016):

'24-Jan-2016'

(*) According to MDN, "modern browsers" means Chrome 24+, Firefox 29+, Internet Explorer 11, Edge 12+, Opera 15+ & Safari nightly build.

@James Wierzba 2016-09-07 22:28:40

Is there a way to check if this function is supported and if not, default to a simpler solution?

@John Slegers 2016-09-12 07:56:47

@JamesWierzba : You could use this polyfill!

@Charles Wood 2017-10-17 00:45:27

This isn't even listed on caniuse.com :/

@Vijay Maheriya 2016-08-29 09:48:16

We have lots of solutions for this, but I think the best of them is Moment.js. So I personally suggest to use Moment.js for date and time operations.

console.log(moment().format('DD-MMM-YYYY'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

@Ced 2016-10-18 17:23:38

why are you including jquery?

@Vijay Maheriya 2016-10-21 06:47:15

Ohh sorry its not require. Thanks @Ced

@Dave Ranjan 2016-12-01 14:18:22

how to provide the date i have to moment.js? I think it always takes current time.

@Vijay Maheriya 2016-12-05 05:59:05

@DaveRanjan i think you need to convert your custom date. So use this : console.log(moment('2016-08-10').format('DD-MMM-YYYY'));

@Dave Ranjan 2016-12-06 07:04:44

Yeah, figured it out later. Thanks :)

@Dave 2016-08-23 13:59:35

Inspired by JD Smith's marvellous regular expression solution, I suddenly had this head-splitting idea:

var D = Date().toString().split(" ");
document.getElementById("demo").innerHTML = D[2] + "-" + D[1] + "-" + D[3];

@JD Smith 2016-09-01 21:46:20

Nice variation if you need it right in the DOM like that!

@Arjun Nayak 2015-12-31 10:01:09

Try this:

function init(){
    var d = new Date();
    var day = d.getDate();
    var x = d.toDateString().substr(4, 3);
    var year = d.getFullYear();
    document.querySelector("#mydate").innerHTML = day + '-' + x + '-' + year;
}
window.onload = init;
<div id="mydate"></div>

Related Questions

Sponsored Content

88 Answered Questions

[SOLVED] How to validate an email address in JavaScript

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

38 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

69 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

49 Answered Questions

[SOLVED] How do I get the current date in JavaScript?

  • 2009-10-07 11:39:02
  • Suresh Chaganti
  • 2508789 View
  • 2170 Score
  • 49 Answer
  • Tags:   javascript date

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

Sponsored Content