By leora


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

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

30 comments

@Prabha 2020-06-28 18:53:39

May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20

what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",

Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11

@Tom 2020-03-27 07:34:57

Works same in IE 11, FF & Chrome (Chrome 80.x shows 12 hours format when en-UK selected).

const d = new Date('2010/08/05 23:45') // 26.3.2020
const dtfUK = new Intl.DateTimeFormat('UK', { year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
const dtfUS = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
console.log(dtfUS.format(d)); // 08/05/2010 11:45:00 PM
console.log(dtfUK.format(d)); // 05.08.2010 23:45:00
/* node.js:
08/05/2010, 11:45:00 PM
2010-08-05 23:45:00
*/

What about something more general ?

var d = new Date('2010-08-10T10:34:56.789Z');
var str = d.toDateString() + // Tue Aug 10 2010
    ' ' + d.toTimeString().split(' ')[0] + // 12:34:56, GMT+0x00 (GMT+0x:00)
    ' ' + (d.getMonth() + 101) + // 108
    ' ' + d.getMilliseconds(); // 789
console.log(str); // Tue Aug 10 2010 12:34:56 108 789
console.log(//   $1 Tue  $2 Aug  $3 11     $4 2020 $5 12   $6 34   $7 56    $8 108  $9 789
    str.replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, '$3-$2-$4 $5:$6.$9 ($1)')
); // 10-Aug-2010 12:34.789 (Tue)
/*
$1: Tue  Week Day string
$2: Aug  Month short text
$3: 11   Day
$4: 2010 Year
$5: 12   Hour
$6: 34   Minute
$7: 56   Seconds
$8: 08   Month
$9: 789  Milliseconds
*/

Or for example 1-line IIFE "library" ;-)

console.log(
    (function (frm, d) { return [d.toDateString(), d.toTimeString().split(' ')[0], (d.getMonth() + 101), d.getMilliseconds()].join(' ').replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, frm); })
    ('$4/$8/$3 $5:$6 ($1)', new Date())
);

You can remove useless parts and / or change indexes if you do not need them.

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

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:

const date = new Date('2010-08-05')
const dateTimeFormat = new Intl.DateTimeFormat('en', { year: 'numeric', month: 'short', day: '2-digit' }) 
const [{ value: month },,{ value: day },,{ value: year }] = dateTimeFormat .formatToParts(date ) 

console.log(`${day}-${month}-${year }`)
console.log(`${day}👠${month}👢${year}`) // just for fun

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).

const d = new Date('2010-08-05')
const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d)
const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d)
const 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).

@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.

@Pieter Venter 2020-01-06 11:03:11

The toLocaleDateString option below (with custom options) is more what I was looking for when I came here. Voting this down and voting other one up

@snow 2020-04-17 14:31:08

Are there any downsides of usin this? What is the difference between using this method and using toLocaleDateString?

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

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:

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

@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

@Piyush 2020-05-10 05:57:22

options given in the value of the key 'day' returns same in both the values -- {day:'2-digit'} OR {day:'numeric'} !

@nycdan 2020-05-21 22:58:58

A perfect 'simple solution' for most situations.

@Kamil Kiełczewski 2020-03-03 12:29:36

Two pure JS one-liners

In this answer I develop JD Smith idea. I was able to shorten the JD Smith regexp

let format= d=> d.toString().replace(/\w+ (\w+) (\d+) (\d+).*/,'$2-$1-$3');

console.log( format(Date()) );

Dave also base on JD Smith idea but he avoid regexp and give very nice solution - I short a little his solution (by change split param) and opaque it in wrapper

let format= (d,a=d.toString().split` `)=> a[2]+"-"+a[1]+"-"+a[3];

console.log( format(Date()) );

@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(" ");
console.log(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!

@Kamil Kiełczewski 2020-03-03 12:21:44

Its Brilliant :)

@riversun 2020-02-17 15:23:22

This function I inspired by java's SimpleDateFormat provides various formats such as:

dd-MMM-yyyy → 17-Jul-2018
yyyyMMdd'T'HHmmssXX → 20180717T120856+0900
yyyy-MM-dd'T'HH:mm:ssXXX → 2018-07-17T12:08:56+09:00
E, dd MMM yyyy HH:mm:ss Z → Tue, 17 Jul 2018 12:08:56 +0900
yyyy.MM.dd 'at' hh:mm:ss Z → 2018.07.17 at 12:08:56 +0900
EEE, MMM d, ''yy → Tue, Jul 17, '18
h:mm a → 12:08 PM
hh 'o''''clock' a, X → 12 o'clock PM, +09

Code example:

function formatWith(formatStr, date, opts) {
    
        if (!date) {
            date = new Date();
        }
    
        opts = opts || {};
    
        let _days = opts.days;
    
        if (!_days) {
            _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        }
    
        let _months = opts.months;
    
        if (!_months) {
            _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        }
    
        const pad = (number, strDigits, isUnpad) => {
            const strNum = number.toString();
            if (!isUnpad && strNum.length > strDigits.length) {
                return strNum;
            } else {
                return ('0000' + strNum).slice(-strDigits.length);
            }
        };
    
        const timezone = (date, letter) => {
            const chunk = [];
            const offset = -date.getTimezoneOffset();
            chunk.push(offset === 0 ? 'Z' : offset > 0 ? '+' : '-');//add Z or +,-
            if (offset === 0) return chunk;
            chunk.push(pad(Math.floor(offset / 60), '00'));//hour
            if (letter === 'X') return chunk.join('');
            if (letter === 'XXX') chunk.push(':');
            chunk.push(pad((offset % 60), '00'));//min
            return chunk.join('');
        };
    
        const ESCAPE_DELIM = '\0';
        const escapeStack = [];
    
        const escapedFmtStr = formatStr.replace(/'.*?'/g, m => {
            escapeStack.push(m.replace(/'/g, ''));
            return ESCAPE_DELIM + (escapeStack.length - 1) + ESCAPE_DELIM;
        });
    
        const formattedStr = escapedFmtStr
            .replace(/y{4}|y{2}/g, m => pad(date.getFullYear(), m, true))
            .replace(/M{3}/g, m => _months[date.getMonth()])
            .replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
            .replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
            .replace(/d{1,2}/g, m => pad(date.getDate(), m))
            .replace(/H{1,2}/g, m => pad(date.getHours(), m))
            .replace(/h{1,2}/g, m => {
                const hours = date.getHours();
                return pad(hours === 0 ? 12 : hours > 12 ? hours - 12 : hours, m);
            })
            .replace(/a{1,2}/g, m => date.getHours() >= 12 ? 'PM' : 'AM')
            .replace(/m{1,2}/g, m => pad(date.getMinutes(), m))
            .replace(/s{1,2}/g, m => pad(date.getSeconds(), m))
            .replace(/S{3}/g, m => pad(date.getMilliseconds(), m))
            .replace(/[E]+/g, m => _days[date.getDay()])
            .replace(/[Z]+/g, m => timezone(date, m))
            .replace(/X{1,3}/g, m => timezone(date, m))
        ;
    
        const unescapedStr = formattedStr.replace(/\0\d+\0/g, m => {
            const unescaped = escapeStack.shift();
            return unescaped.length > 0 ? unescaped : '\'';
        });
    
        return unescapedStr;
    }

    //Let's format with above function
    const dateStr = '2018/07/17 12:08:56';
    const date = new Date(dateStr);
    const patterns = [
        "dd-MMM-yyyy",
        "yyyyMMdd'T'HHmmssXX",//ISO8601
        "yyyy-MM-dd'T'HH:mm:ssXXX",//ISO8601EX
        "E, dd MMM yyyy HH:mm:ss Z",//RFC1123(RFC822) like email
        "yyyy.MM.dd 'at' hh:mm:ss Z",//hh shows 1-12
        "EEE, MMM d, ''yy",
        "h:mm a",
        "hh 'o''''clock' a, X",
    ];
    
    
    for (let pattern of patterns) {
        console.log(`${pattern} → ${formatWith(pattern, date)}`);
    }

And you can use this as a library

Also released as a NPM module.You can use this on node.js or use this from CDN for browser.

nodejs

const {SimpleDateFormat} = require('@riversun/simple-date-format');

on browser

<script src="https://cdn.jsdelivr.net/npm/@riversun/[email protected]/dist/simple-date-format.js"></script>

Write code as follows.

const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"

Source code here on github:

https://github.com/riversun/simple-date-format

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

You should have a look at DayJs It's a remake of momentJs but modular architecture oriented so 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>

@JD Smith 2015-10-14 17:25:00

I can get your requested format in one line using no libraries and no Date methods, just regex:

var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')

In my testing, this works reliably in the major browsers (Chrome, Safari, Firefox and IE.) As @RobG pointed out, the output of Date.prototype.toString() is implementation-dependent, so just test the output to be sure it works right in your JavaScript engine. You can even add some code to test the string output and make sure it's matching what you expect before you do the regex replace.

@John 2016-04-30 11:44:07

console.log(new Date().toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2‌​-$1-$3'));

@JD Smith 2018-12-06 21:18:20

@André - I agree. If this were my code, I would most certainly include a comment alongside it that explains the regex and gives an example of the input and corresponding output.

@unruledboy 2020-01-18 06:43:25

how about time part (HH:mm:ss) ?

@JD Smith 2020-02-03 22:22:08

@unruledboy var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s(\S+)\‌​s.*/,'$2-$1-$3 $4'); - or to get just the time part without the date itself, use: var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s(\S+)\‌​s.*/,'$4');

@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()
// The above yields e.g. 'Mon Jan 06 2020'

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

@Tofandel 2020-01-08 20:19:11

It is but only by IE11, IE10- have been out of life way before this existed so it's understandable. 92% from caniuse, which is pretty good caniuse.com/#search=datetimeformat

@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'));

@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.

Related Questions

Sponsored Content

69 Answered Questions

[SOLVED] How do I correctly clone a JavaScript object?

53 Answered Questions

86 Answered Questions

[SOLVED] How do JavaScript closures work?

27 Answered Questions

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

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

55 Answered Questions

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

3 Answered Questions

40 Answered Questions

[SOLVED] For-each over an array in JavaScript

39 Answered Questions

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

67 Answered Questions

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

Sponsored Content