By leora

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

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


@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


@Ryan Loggerythm 2016-04-07 23:58:39

wow, it really pays to scroll down. your answer blows away the one with 300+ votes. great job.

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

I think you mean toLocaleString/toLocaleDateString... The method toDateString doesn't accept any parameters.…

@Sammy 2016-11-26 19:57:56

Thank you for this useful answer. This should be the accepted one. Great work.

@swyx 2017-02-09 02:11:07

agree, thank you for this answer

@M. Herold 2017-07-20 00:31:47

Oh my lord, this is the correct answer. I can't believe how hard it was to Google for this information.

@Meher Ranjan 2017-08-30 14:54:48

this is perfect!

@Shantaram Tupe 2017-09-20 13:58:50

thanks this helped me !!!, no need to add Extra JS file

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

@MA1 2017-11-23 18:26:47

awesome. solved my issue

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

@ajeet kanojia 2017-12-18 07:26:20

Thanks, I will add this

@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 :)

@ajeet kanojia 2018-05-24 08:52:40

Thanks for the edit @Vadim Ovchinnikov

@Vadim Ovchinnikov 2018-05-24 09:05:40

Thanks for the greatest answer:) @ajeetkanojia

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

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

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

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

For any one looking for a really simple ES6 solution to copy and paste.

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

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

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

I post here for future reference and ready-to-copy-paste-ness, 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

Hi check if this helps with your 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.

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

new Date().toLocaleDateString()

// "3/21/2018"

More documentation at

@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

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

I know someone might say that this is silly solution but it does do the trick to remove the unnecessary information from date.

yourDateObject produces:

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

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

Wed Dec 13 2017

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

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

toISOString: Show ISO 8601 date and time.

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

toJSON: Stringifier for JSON.

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

toLocaleDateString: Implementation dependent, a date in locale format.

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

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

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

toLocaleTimeString: Implementation dependent, a time in locale format.

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

toString: Generic toString for Date.

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

@deFreitas 2017-12-03 22:30:57


@AXL 2018-01-31 07:54:13

best documented solution in JS as OP asked. Nice!

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

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


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) {
    return (hours + 24) % 12 || 12;
  getAmPm: function (hours) {
    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'));

Format description was take Ionic Framework (does not support Z,UTC Timezone Offset)

Not thoroughly tested

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


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



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:

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".
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".


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


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.


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


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


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.


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


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


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


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


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


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


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


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


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

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

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

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:


For more details about ECMAScript Internationalization API (Intl), visit here.

@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 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):


(*) 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 :/

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

<script src="//"></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>

@Gene R 2015-11-18 08:36:58

There is a new library,, for localized formatting of JavaScript numbers, dates and JSON dates (Microsoft or ISO8601).


new Date('2015-1-1').to('dd.MM.yy')         // Outputs 01.01.2015
"2015-01-01T10:11:12.123Z".to('dd.MM.yy')   // Outputs 01.01.2015

There are also custom short patterns defined in the localization file ({culture}.js). Example (

new Date('2015-1-1').to('d')                // Outputs 1.01.2015

And a multiformatting ability:

smarti.format('{0:n2} + {1:n2} = {2:n2}', 1, 2, 3)   // Output: 1,00 + 2,00 = 3,00

@SaidB 2015-11-11 08:46:59

I use the following. It is simple and works fine.

 var dtFormat = require('dtformat');
   var today = new Date();
   dtFormat(today, "dddd, mmmm dS, yyyy, h:MM:ss TT");

Or this:

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

@Mite Mitreski 2014-12-24 10:15:23

Plain JavaScript is the best pick for small onetimers.

On the other hand, if you need more date stuff, MomentJS is a great solution.

For example:

moment().format('YYYY-MM-DD HH:m:s');     // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 11 hours ago
moment().endOf('day').fromNow();          // in 13 hours

@morhook 2017-03-15 12:29:55

I think you will probably need more date stuff!!

@Amit Kumar Gupta 2016-07-30 16:58:28

This is how I implemented for my npm plugins

var monthNames = [
  "January", "February", "March",
  "April", "May", "June", "July",
  "August", "September", "October",
  "November", "December"

var Days = [
  "Sunday", "Monday", "Tuesday", "Wednesday",
  "Thursday", "Friday", "Saturday"

var formatDate = function(dt,format){
  format = format.replace('ss', pad(dt.getSeconds(),2));
  format = format.replace('s', dt.getSeconds());
  format = format.replace('dd', pad(dt.getDate(),2));
  format = format.replace('d', dt.getDate());
  format = format.replace('mm', pad(dt.getMinutes(),2));
  format = format.replace('m', dt.getMinutes());
  format = format.replace('MMMM', monthNames[dt.getMonth()]);
  format = format.replace('MMM', monthNames[dt.getMonth()].substring(0,3));
  format = format.replace('MM', pad(dt.getMonth()+1,2));
  format = format.replace(/M(?![ao])/, dt.getMonth()+1);
  format = format.replace('DD', Days[dt.getDay()]);
  format = format.replace(/D(?!e)/, Days[dt.getDay()].substring(0,3));
  format = format.replace('yyyy', dt.getFullYear());
  format = format.replace('YYYY', dt.getFullYear());
  format = format.replace('yy', (dt.getFullYear()+"").substring(2));
  format = format.replace('YY', (dt.getFullYear()+"").substring(2));
  format = format.replace('HH', pad(dt.getHours(),2));
  format = format.replace('H', dt.getHours());
  return format;

pad = function(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;

@lbrahim 2016-11-01 11:09:58

This should be made into a npm package itself

@Amit Kumar Gupta 2016-11-02 06:53:23

It is a good suggestion. I have created one. Now I realised that there is already similar packages available. So deleting my package.

@lbrahim 2016-11-02 08:11:08

Which package are you referring to?

@Amit Kumar Gupta 2016-11-02 09:35:48

@ntaso 2017-02-22 09:41:01

This has a bug: Month names are replaced first, then the name of the month will be replaced as well. For example March will become 3arch with this code.

@ntaso 2017-02-22 09:46:52

Change line for 'M' to format = format.replace("M(?!M)", (dt.getMonth()+1).toString()); and put it above line with 'MMMM'

@Amit Kumar Gupta 2017-02-23 06:17:39

Thanks I've update the answer with a small update

@zest 2016-02-09 22:00:55

var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();

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

Update: As @RobG pointed out, the output of Date.prototype.toString() is implementation-dependent. So, use with caution and modify if necessary for your implementations if you use this solution. In my testing, this works reliably in North America where the major browsers (Chrome, Safari, Firefox and IE) all return the same string format.

@Leo Moore 2015-11-05 16:53:01

Thanks JD, neat and compact solution

@Sanchitos 2015-11-18 14:03:08

Best solution, no libaries. Straight to the point.

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

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

@Dave 2016-08-23 12:57:48

If you fancy a short, human-readable, function - this is easily adjustable to suit you.

The timeStamp parameter is milliseconds from 1970 - it is returned by new Date().getTime() and many other devices...

OK, I changed my mind. I included an extra function for zero padding. Curses!

 function zeroPad(aNumber) {
     return ("0"+aNumber).slice(-2);
 function humanTime(timeStamp) {
    var M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var D = new Date(timeStamp); // 23 Aug 2016 16:45:59 <-- Desired format.
    return D.getDate() + " " + M[D.getMonth()] + " " + D.getFullYear() + " " + D.getHours() + ":" + zeroPad(d.getMinutes()) + ":" + zeroPad(D.getSeconds());

@Ron Royston 2016-05-03 22:31:17

2.39KB minified. One file.

10-Aug-2010 would be:

var str = clock.month
str.charAt(0).toUpperCase() + str.slice(1,3); //gets you "Aug"
console.log( + '-' + str + '-' + clock.year); //gets you 10-Aug-2010

@John Slegers 2016-06-30 08:25:35

Still having to do stuff like str.charAt(0).toUpperCase() + str.slice(1,3); kinda defeats the purpose of using a library. Why don't you add out-of-the-box support for three letter month formats? Also, you might want to consider adding internationalization to you library, as a library like this would be kinda useless for non-English websites without it!

@JP de la Torre 2015-12-21 16:34:53

Short, widely compatible approach:

function formatDate(date) {
    .replace(/^(\d+)-(\d+)-(\d+).*$/, // Only extract Y-M-D
        function (a,y,m,d) {
            return [
                d, // Day
                ['Jan','Feb','Mar','Apr','May','Jun',  // Month Names
                [m-1], // Month
                y  // Year
            ].join('-') // Stitch together

Or, as a single line:

date.toISOString().replace(/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+).(\d+)Z$/, function (a,y,m,d) {return [d,['Jan','Feb','Mar','Apr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'][m-1],y].join('-')})

@RobertPitt 2010-08-23 23:35:47

Use the date.format library:

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


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

dateformat on npm

@RobertPitt 2010-08-25 18:33:15

this might seem like the longer solution but compressed and used on a site that uses dates a fair bit would be the better solution!

@user2451227 2014-04-22 11:29:28

His code for "L" for cantiseconds is wrong, he should remove "L > 99 ?" part... Other than that, it's pretty neat, if not too well localizable.

@David 2015-10-21 15:29:08

This solution is also available as an npm package:

@Amit Kumar Gupta 2016-07-30 16:16:40

There are 14 open issues with the above plugin. Even I found one :(

@Hooli 2016-11-12 17:40:00

I get require is not defined

@htafoya 2017-05-29 16:25:13

how to change Lang for this plugin?

@Luke Pring 2017-08-25 12:23:21

OP asked for JS solution

@Drew Dara-Abrams 2018-07-06 21:31:58

If you're going to the trouble of importing a external dependency, I'd recommend using moment.js. It can do this type of date formatting: And it has much more functionality.

@voidsstr 2018-08-15 04:59:56

this is the most concise correct answer

@Peter 2015-11-11 08:31:57

If you are already using ExtJS in your project you could use Ext.Date:

var date = new Date();
Ext.Date.format(date, "d-M-Y");



@webzy 2014-11-17 13:32:55

If you are using jQuery UI in your code, there is an inbuilt function called formatDate(). I am using it this way to format today's date:

var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));

You can see many other examples of formatting date in the jQuery UI documentation.

@Sébastien 2011-12-30 05:33:07

I think you can just use the non-standard Date method toLocaleFormat(formatString)

formatString: A format string in the same format expected by the strftime() function in C.

var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011


@fitzgeraldsteele 2012-06-11 21:02:25

toLocaleFormat() appears to only work in Firefox. Both IE and Chrome are failing for me.

@apocalypz 2014-07-09 12:44:13

Chrome has .toLocaleString('en') method. As it seems new browser supports this…

@Carson Reinke 2015-02-09 20:09:55

@santa 2016-02-26 14:10:20

this would be the best solution if everyone could f*in implement it. damn you ie/chrome

@Michael Scheper 2016-09-22 19:16:01

@santa: Indeed. Maybe there was a fair reason not to follow Mozilla's lead on this, but the fact that even ES6 doesn't have a standard function for this shows that it's still a hacker's language, not a developer's language.

@Josh Unger 2016-12-20 23:19:18

new Intl.DateTimeFormat appears to be the replacement…

@Manuel Ortiz 2018-08-08 18:12:11

7 years later this function still does not work in other browsers and was deprecated in Firefox Deprecated_toLocaleFormat

Related Questions

Sponsored Content

26 Answered Questions

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

62 Answered Questions

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

73 Answered Questions

[SOLVED] How to validate an email address in JavaScript?

25 Answered Questions

39 Answered Questions

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

  • 2009-10-07 11:39:02
  • Suresh
  • 1900921 View
  • 1697 Score
  • 39 Answer
  • Tags:   javascript date

35 Answered Questions

[SOLVED] Where can I find documentation on formatting a date in JavaScript?

36 Answered Questions

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

88 Answered Questions

[SOLVED] How do JavaScript closures work?

59 Answered Questions

[SOLVED] How do I redirect to another webpage?

48 Answered Questions

Sponsored Content