By leora


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

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

30 comments

@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)
    ;
    return 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('MMMM', MMMM).replace('MMM', MMM).replace('MM', MM).replace('M', M)
      .replace('EEEE', EEEE).replace('EEE', EEE)
      .replace('yyyy', yyyy)
      .replace('yy', yy)
      .replace('aaa', aaa)
    ;
}
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

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

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

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

Use toLocaleDateString()

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

The values you can passed in options for different keys:

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

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

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

For different languages:

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

You can use more language options.

For example

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

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

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

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

References:

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

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

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

@sg28 2019-03-06 01:21:41

Take a Bow, ---

@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 details about ECMAScript Internationalization API (Intl), visit here.

@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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@Annjawn 2018-11-15 20:11:28

How about a 2kb library called DayJS - github.com/iamkun/dayjs

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

Can we realistically avoid moment and luxon these days?

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

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

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

If you need to change the delimiters:

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

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

new Date().toLocaleDateString()

// "3/21/2018"

More documentation at developer.mozilla.org

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

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

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

Custom formatting function:

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

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

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

The OP format may be generated like:

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

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

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

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

Standard ECMAScript formatting functions:

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

toDateString: Implementation dependent, show only the date.

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

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

toISOString: Show ISO 8601 date and time.

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

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

toJSON: Stringifier for JSON.

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

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

toLocaleDateString: Implementation dependent, a date in locale format.

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

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

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

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

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

toLocaleTimeString: Implementation dependent, a time in locale format.

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

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

toString: Generic toString for Date.

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

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

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

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

Examples snippets:

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

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

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

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

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

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

Result Is: "12-Oct-2017"

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

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

Syntax

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

Parameters

locales

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

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

Options

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

localeMatcher

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

timeZone

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

hour12

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

formatMatcher

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

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

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

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

weekday

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

era

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

year

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

month

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

day

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

hour

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

minute

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

second

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

timeZoneName

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

Check Online

More Details

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

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

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

  return out;
}

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

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

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

See repl.it example for details.

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

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

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

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

'24-Jan-2016'

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

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

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

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

@JamesWierzba : You could use this polyfill!

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

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

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

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

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

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

why are you including jquery?

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

Ohh sorry its not require. Thanks @Ced

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

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

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

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

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

Yeah, figured it out later. Thanks :)

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

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

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

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

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

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

Try this:

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

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

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

Example:

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 (smarti.to.{culture}.js). Example (smarti.to.et-EE.js):

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

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

@Gerry 2019-04-11 15:35:43

moment is obsolete, use luxon

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

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

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

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

Related Questions

Sponsored Content

70 Answered Questions

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

3 Answered Questions

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

33 Answered Questions

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

43 Answered Questions

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

  • 2009-10-07 11:39:02
  • Suresh
  • 2218373 View
  • 1934 Score
  • 43 Answer
  • Tags:   javascript date

79 Answered Questions

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

86 Answered Questions

[SOLVED] How do JavaScript closures work?

26 Answered Questions

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

37 Answered Questions

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

35 Answered Questions

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

Sponsored Content