javascript - yyyy - typescript date format

Where can I find documentation on formatting a date in JavaScript? (20)

Where is the documentation which lists the format specifiers supported by the Date() object?

I stumbled across this today and was quite surprised that no one took the time to answer this simple question. True, there are many libraries out there to help with date manipulation. Some are better than others. But that wasn't the question asked.

AFAIK, pure JavaScript doesn't support format specifiers the way you have indicated you'd like to use them. But it does support methods for formatting dates and/or times, such as .toLocaleDateString(), .toLocaleTimeString(), and .toUTCString().

The Date object reference I use most frequently is on the website (but a quick Google search will reveal many more that may better meet your needs).

Also note that the Date Object Properties section provides a link to prototype, which illustrates some ways you can extend the Date object with custom methods. There has been some debate in the JavaScript community over the years about whether or not this is best practice, and I am not advocating for or against it, just pointing out its existence.

I noticed that JavaScript's new Date() function is very smart in accepting dates in several formats.

Xmas95 = new Date("25 Dec, 1995 23:15:00")
Xmas95 = new Date("2009 06 12,12:52:39")
Xmas95 = new Date("20 09 2006,12:52:39")

I could not find documentation anywhere showing all the valid string formats while calling new Date() function.

This is for converting a string to a date. If we look at the opposite side, that is, converting a date object to a string, until now I was under the impression that JavaScript doesn't have a built-in API to format a date object into a string.

Editor's note: The following approach is the asker's attempt that worked on a particular browser but does not work in general; see the answers on this page to see some actual solutions.

Today, I played with the toString() method on the date object and surprisingly it serves the purpose of formatting date to strings.

var d1 = new Date();
d1.toString('yyyy-MM-dd');       //Returns "2009-06-29" in Internet Explorer, but not Firefox or Chrome
d1.toString('dddd, MMMM ,yyyy')  //Returns "Monday, June 29,2009" in Internet Explorer, but not Firefox or Chrome

Also here I couldn't find any documentation on all the ways we can format the date object into a string.

Where is the documentation which lists the format specifiers supported by the Date() object?

The Short Answer

There is no “universal” documentation that javascript caters to; every browser that has javascript is really an implementation. However, there is a standard that most modern browsers tend to follow, and that’s the EMCAScript standard; the ECMAScript standard strings would take, minimally, a modified implementation of the ISO 8601 definition.

In addition to this, there is a second standard set forward by the IETF that browsers tend to follow as well, which is the definition for timestamps made in the RFC 2822. Actual documentation can be found in the references list at the bottom.

From this you can expect basic functionality, but what “ought” to be is not inherently what “is”. I’m going to go a little in depth with this procedurally though, as it appears only three people actually answered the question (Scott, goofballLogic, and peller namely) which, to me, suggests most people are unaware of what actually happens when you create a Date object.

The Long Answer

Where is the documentation which lists the format specifiers supported by the Date() object?

To answer the question, or typically even look for the answer to this question, you need to know that javascript is not a novel language; it’s actually an implementation of ECMAScript, and follows the ECMAScript standards (but note, javascript also actually pre-dated those standards; EMCAScript standards are built off the early implementation of LiveScript/JavaScript). The current ECMAScript standard is 5.1 (2011); at the time that the question was originally asked (June ’09), the standard was 3 (4 was abandoned), but 5 was released shortly after the post at the end of 2009. This should outline one problem; what standard a javascript implementation may follow, may not reflect what is actually in place, because a) it’s an implementation of a given standard, b) not all implementations of a standard are puritan, and c) functionality is not released in synchronization with a new standard as d) an implementation is a constant work in progress

Essentially, when dealing with javascript, you’re dealing with a derivative (javascript specific to the browser) of an implementation (javascript itself). Google’s V8, for example, implements ECMAScript 5.0, but Internet Explorer’s JScript doesn’t attempt to conform to any ECMAScript standard, yet Internet Explorer 9 does conform to ECMAScript 5.0.

When a single argument is passed to new Date(), it casts this function prototype:

new Date(value)

When two or more arguments are passed to new Date(), it casts this function prototype:

new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )

Both of those functions should look familiar, but this does not immediately answer your question and what quantifies as an acceptable “date format” requires further explanation. When you pass a string to new Date(), it will call the prototype (note that I'm using the word prototype loosely; the versions may be individual functions, or it may be part of a conditional statement in a single function) for new Date(value) with your string as the argument for the “value” parameter. This function will first check whether it is a number or a string. The documentation for this function can be found here:

From this, we can deduce that to get the string formatting allowed for new Date(value), we have to look at the method Date.parse(string). The documentation for this method can be found here:

And we can further infer that dates are expected to be in a modified ISO 8601 Extended Format, as specified here:

However, we can recognize from experience that javascript’s Date object accepts other formats (enforced by the existence of this question in the first place), and this is okay because ECMAScript allows for implementation specific formats. However, that still doesn’t answer the question of what documentation is available on the available formats, nor what formats are actually allowed. We’re going to look at Google’s javascript implementation, V8; please note I’m not suggesting this is the “best” javascript engine (how can one define “best” or even “good”) and one cannot assume that the formats allowed in V8 represent all formats available today, but I think it’s fair to assume they do follow modern expectations.

Google’s V8, date.js, DateConstructor

Looking at the DateConstructor function, we can deduce we need to find the DateParse function; however, note that “year” is not the actual year and is only a reference to the “year” parameter.

Google’s V8, date.js, DateParse

This calls %DateParseString, which is actually a run-time function reference for a C++ function. It refers to the following code:

Google’s V8,, %DateParseString

The function call we’re concerned with in this function is for DateParser::Parse(); ignore the logic surrounding those function calls, these are just checks to conform to the encoding type (ASCII and UC16). DateParser::Parse is defined here:

Google's V8, dateparser-inl.h, DateParser::Parse

This is the function that actually defines what formats it accepts. Essentially, it checks for the EMCAScript 5.0 ISO 8601 standard and if it is not standards compliant, then it will attempt to build the date based on legacy formats. A few key points based on the comments:

  1. Words before the first number that are unknown to the parser are ignored.
  2. Parenthesized text are ignored.
  3. Unsigned numbers followed by “:” are interpreted as a “time component”.
  4. Unsigned numbers followed by “.” are interpreted as a “time component”, and must be followed by milliseconds.
  5. Signed numbers followed by the hour or hour minute (e.g. +5:15 or +0515) are interpreted as the timezone.
  6. When declaring the hour and minute, you can use either “hh:mm” or “hhmm”.
  7. Words that indicate a time zone are interpreted as a time zone.
  8. All other numbers are interpreted as “date components”.
  9. All words that start with the first three digits of a month are interpreted as the month.
  10. You can define minutes and hours together in either of the two formats: “hh:mm” or “hhmm”.
  11. Symbols like “+”, “-“ and unmatched “)” are not allowed after a number has been processed.
  12. Items that match multiple formats (e.g. 1970-01-01) are processed as a standard compliant EMCAScript 5.0 ISO 8601 string.

So this should be enough to give you a basic idea of what to expect when it comes to passing a string into a Date object. You can further expand upon this by looking at the following specification that Mozilla points to on the Mozilla Developer Network (compliant to the IETF RFC 2822 timestamps):

The Microsoft Developer Network additionally mentions an additional standard for the Date object: ECMA-402, the ECMAScript Internationalization API Specification, which is complementary to the ECMAScript 5.1 standard (and future ones). That can be found here:

In any case, this should aid in highlighting that there is no "documentation" that universally represents all implementations of javascript, but there is still enough documentation available to make reasonable sense of what strings are acceptable for a Date object. Quite the loaded question when you think about it, yes? :P



Custom formatting function:

For fixed formats, a simple function make the job. Following example generate the international format YYYY-MM-DD:

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

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. There are a couple of good examples in this same page.

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 11 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"

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

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

JsSimpleDateFormat is a library that can format the date object and parse the formatted string back to Date object. It uses the Java format (SimpleDateFormat class). The name of months and days can be localized.


var sdf = new JsSimpleDateFormat("EEEE, MMMM dd, yyyy");
var formattedString = sdf.format(new Date());
var dateObject = sdf.parse("Monday, June 29, 2009");

Example code:

var d = new Date();
var time = d.toISOString().replace(/.*?T(\d+:\d+:\d+).*/, "$1");



Framework free, limited but light

var d = (new Date()+'').split(' ');
// ["Tue", "Sep", "03", "2013", "21:54:52", "GMT-0500", "(Central", "Daylight", "Time)"]

[d[3], d[1], d[2], d[4]].join(' ');
// "2013 Sep 03 21:58:03"

Having looked through several of the options provided in other answers, I decided to write my own limited but simple solution that others may also find useful.

* Format date as a string
* @param date - a date object (usually "new Date();")
* @param format - a string format, eg. "DD-MM-YYYY"
function dateFormat(date, format) {
    // Calculate date parts and replace instances in format string accordingly
    format = format.replace("DD", (date.getDate() < 10 ? '0' : '') + date.getDate()); // Pad with '0' if needed
    format = format.replace("MM", (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1)); // Months are zero-based
    format = format.replace("YYYY", date.getFullYear());
    return format;

Example usage:

console.log("The date is: " + dateFormat(new Date(), "DD/MM/YYYY"));

I love 10 ways to format time and date using JavaScript and Working with Dates.

Basically, you have three methods and you have to combine the strings for yourself:

getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year


var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
console.log(curr_date + "-" + curr_month + "-" + curr_year);

I made this very simple formatter, it's cut/n/pastable (Updated with neater version):

function DateFmt(fstr) {
  this.formatString = fstr

  var mthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  var dayNames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
  var zeroPad = function(number) {
     return ("0"+number).substr(-2,2);

  var dateMarkers = {
    d:['getDate',function(v) { return zeroPad(v)}],
    m:['getMonth',function(v) { return zeroPad(v+1)}],
    n:['getMonth',function(v) { return mthNames[v]; }],
    w:['getDay',function(v) { return dayNames[v]; }],
    H:['getHours',function(v) { return zeroPad(v)}],
    M:['getMinutes',function(v) { return zeroPad(v)}],
    S:['getSeconds',function(v) { return zeroPad(v)}],

  this.format = function(date) {
    var dateTxt = this.formatString.replace(/%(.)/g, function(m, p) {
      var rv = date[(dateMarkers[p])[0]]()

      if ( dateMarkers[p][1] != null ) rv = dateMarkers[p][1](rv)

      return rv


    return dateTxt


fmt = new DateFmt("%w %d:%n:%y - %H:%M:%S  %i")
v = fmt.format(new Date())

If you are already using jQuery UI in your project, you can use the built-in datepicker method for formatting your date object:

$.datepicker.formatDate('yy-mm-dd', new Date(2007, 1 - 1, 26));

However, the datepicker only formats dates, and cannot format times.

Have a look at jQuery UI datepicker formatDate, the examples.

If you don't need all the features that a library like Moment.js provides, then you can use my port of strftime. It's lightweight (1.35 KB vs. 57.9 KB minified compared to Moment.js 2.15.0) and provides most of the functionality of strftime().

/* Port of strftime(). Compatibility notes:
 * %c - formatted string is slightly different
 * %D - not implemented (use "%m/%d/%y" or "%d/%m/%y")
 * %e - space is not added
 * %E - not implemented
 * %h - not implemented (use "%b")
 * %k - space is not added
 * %n - not implemented (use "\n")
 * %O - not implemented
 * %r - not implemented (use "%I:%M:%S %p")
 * %R - not implemented (use "%H:%M")
 * %t - not implemented (use "\t")
 * %T - not implemented (use "%H:%M:%S")
 * %U - not implemented
 * %W - not implemented
 * %+ - not implemented
 * %% - not implemented (use "%")
 * strftime() reference:
 * Day of year (%j) code based on Joe Orost's answer:
 * http://.com/questions/8619879/javascript-calculate-the-day-of-the-year-1-366
 * Week number (%V) code based on Taco van den Broek's prototype:
function strftime(sFormat, date) {
  if (!(date instanceof Date)) date = new Date();
  var nDay = date.getDay(),
    nDate = date.getDate(),
    nMonth = date.getMonth(),
    nYear = date.getFullYear(),
    nHour = date.getHours(),
    aDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    aMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    aDayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
    isLeapYear = function() {
      if (nYear&3!==0) return false;
      return nYear%100!==0 || year%400===0;
    getThursday = function() {
      var target = new Date(date);
      target.setDate(nDate - ((nDay+6)%7) + 3);
      return target;
    zeroPad = function(nNum, nPad) {
      return ('' + (Math.pow(10, nPad) + nNum)).slice(1);
  return sFormat.replace(/%[a-z]/gi, function(sMatch) {
    return {
      '%a': aDays[nDay].slice(0,3),
      '%A': aDays[nDay],
      '%b': aMonths[nMonth].slice(0,3),
      '%B': aMonths[nMonth],
      '%c': date.toUTCString(),
      '%C': Math.floor(nYear/100),
      '%d': zeroPad(nDate, 2),
      '%e': nDate,
      '%F': date.toISOString().slice(0,10),
      '%G': getThursday().getFullYear(),
      '%g': ('' + getThursday().getFullYear()).slice(2),
      '%H': zeroPad(nHour, 2),
      '%I': zeroPad((nHour+11)%12 + 1, 2),
      '%j': zeroPad(aDayCount[nMonth] + nDate + ((nMonth>1 && isLeapYear()) ? 1 : 0), 3),
      '%k': '' + nHour,
      '%l': (nHour+11)%12 + 1,
      '%m': zeroPad(nMonth + 1, 2),
      '%M': zeroPad(date.getMinutes(), 2),
      '%p': (nHour<12) ? 'AM' : 'PM',
      '%P': (nHour<12) ? 'am' : 'pm',
      '%s': Math.round(date.getTime()/1000),
      '%S': zeroPad(date.getSeconds(), 2),
      '%u': nDay || 7,
      '%V': (function() {
              var target = getThursday(),
                n1stThu = target.valueOf();
              target.setMonth(0, 1);
              var nJan1 = target.getDay();
              if (nJan1!==4) target.setMonth(0, 1 + ((4-nJan1)+7)%7);
              return zeroPad(1 + Math.ceil((n1stThu-target)/604800000), 2);
      '%w': '' + nDay,
      '%x': date.toLocaleDateString(),
      '%X': date.toLocaleTimeString(),
      '%y': ('' + nYear).slice(2),
      '%Y': nYear,
      '%z': date.toTimeString().replace(/.+GMT([+-]\d+).+/, '$1'),
      '%Z': date.toTimeString().replace(/.+\((.+?)\)$/, '$1')
    }[sMatch] || sMatch;

Sample usage:

strftime('%F'); // Returns "2016-09-15"
strftime('%A, %B %e, %Y'); // Returns "Thursday, September 15, 2016"

// You can optionally pass it a Date object...

strftime('%x %X', new Date('1/1/2016')); // Returns "1/1/2016 12:00:00 AM"

The latest code is available here:

Just another option, which I wrote:

DP_DateExtensions Library

Not sure if it'll help, but I've found it useful in several projects - looks like it'll do what you need.

Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.

No reason to consider it if you're already using a framework (they're all capable), but if you just need to quickly add date manipulation to a project give it a chance.

Just to continue gongzhitaao's solid answer - this handles AM/PM

 Date.prototype.format = function (format) //author: meizz
    var hours = this.getHours();
    var ttime = "AM";
    if(format.indexOf("t") > -1 && hours > 12)
        hours = hours - 12;
        ttime = "PM";

var o = {
    "M+": this.getMonth() + 1, //month
    "d+": this.getDate(),    //day
    "h+": hours,   //hour
    "m+": this.getMinutes(), //minute
    "s+": this.getSeconds(), //second
    "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
    "S": this.getMilliseconds(), //millisecond,
    "t+": ttime

if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
  (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o) if (new RegExp("(" + k + ")").test(format))
    format = format.replace(RegExp.$1,
      RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length));
return format;

Many frameworks (that you might already be using) have date formatting that you may not be aware of. jQueryUI was already mentioned, but other frameworks such as Kendo UI (Globalization), Yahoo UI (Util) and AngularJS have them as well.

// 11/6/2000
kendo.toString(new Date(value), "d")

// Monday, November 06, 2000
kendo.toString(new Date(2000, 10, 6), "D")

Personally, because I use both PHP and jQuery/javascript in equal measures, I use the date function from php.js

Using a library that uses the same format strings as something I already know is easier for me, and the manual containing all of the format string possibilities for the date function is of course online at

You simply include the date.js file in your HTML using your preferred method then call it like this:

var d1=new Date();
var datestring = date('Y-m-d', d1.valueOf()/1000);

You can use d1.getTime() instead of valueOf() if you want, they do the same thing.

The divide by 1000 of the javascript timestamp is because a javascript timestamp is in miliseconds but a PHP timestamp is in seconds.

The correct way to format a date to return "2012-12-29" is with the script from JavaScript Date Format:

var d1 = new Date();
return d1.format("dd-m-yy");

This code does NOT work:

var d1 = new Date();

The functionality you cite is not standard Javascript, not likely to be portable across browsers and therefore not good practice. The ECMAScript 3 spec leaves the parse and output formats function up to the Javascript implementation. ECMAScript 5 adds a subset of ISO8601 support. I believe the toString() function you mention is an innovation in one browser (Mozilla?)

Several libraries provide routines to parameterize this, some with extensive localization support. You can also check out the methods in

You can just expand the Date Object with a new format method as noted by meizz, below is the code given by the author. And here is a jsfiddle.

Date.prototype.format = function(format) //author: meizz
  var o = {
    "M+" : this.getMonth()+1, //month
    "d+" : this.getDate(),    //day
    "h+" : this.getHours(),   //hour
    "m+" : this.getMinutes(), //minute
    "s+" : this.getSeconds(), //second
    "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
    "S" : this.getMilliseconds() //millisecond

  if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
    (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)if(new RegExp("("+ k +")").test(format))
    format = format.replace(RegExp.$1,
      RegExp.$1.length==1 ? o[k] :
        ("00"+ o[k]).substr((""+ o[k]).length));
  return format;

alert(new Date().format("yyyy-MM-dd"));
alert(new Date("january 12 2008 11:12:30").format("yyyy-MM-dd h:mm:ss"));

You may find useful this modification of date object, which is smaller than any library and is easily extendable to support different formats:


  • It uses Object.keys() which is undefined in older browsers so you may need implement polyfill from given link.


Date.prototype.format = function(format) {
    // set default format if function argument not provided
    format = format || 'YYYY-MM-DD hh:mm';

    var zeropad = function(number, length) {
            number = number.toString();
            length = length || 2;
            while(number.length < length)
                number = '0' + number;
            return number;
        // here you can define your formats
        formats = {
            YYYY: this.getFullYear(),
            MM: zeropad(this.getMonth() + 1),
            DD: zeropad(this.getDate()),
            hh: zeropad(this.getHours()),
            mm: zeropad(this.getMinutes())
        pattern = '(' + Object.keys(formats).join(')|(') + ')';

    return format.replace(new RegExp(pattern, 'g'), function(match) {
        return formats[match];


var now = new Date;
// outputs: 2015-02-09 11:47
var yesterday = new Date('2015-02-08');
console.log(yesterday.format('hh:mm YYYY/MM/DD'));
// outputs: 00:00 2015/02/08