Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Example:

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

Moment.js

It is a (lightweight)* JavaScript date library for parsing, manipulating, and formatting dates.

var a = moment([2010, 1, 14, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
a.format("ddd, hA");                       // "Sun, 3PM"

(*) lightweight meaning 9.3KB minified + gzipped in the smallest possible setup (feb 2014)


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.


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.

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

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 w3schools.com 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.


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:

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.2

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:

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2

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

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

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

https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#141

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

https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#270

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

Google’s V8, runtime.cc, %DateParseString

https://code.google.com/p/v8/source/browse/trunk/src/runtime.cc?r=18400#9559

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

https://code.google.com/p/v8/source/browse/trunk/src/dateparser-inl.h?r=18400#36

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

https://www.rfc-editor.org/rfc/rfc2822#page-14

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:

http://www.ecma-international.org/ecma-402/1.0/

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

References

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.2

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

https://www.rfc-editor.org/rfc/rfc2822#page-14

http://www.ecma-international.org/ecma-402/1.0/

https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#141

https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#270

https://code.google.com/p/v8/source/browse/trunk/src/runtime.cc?r=18400#9559

https://code.google.com/p/v8/source/browse/trunk/src/dateparser-inl.h?r=18400#36

Resources

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

http://msdn.microsoft.com/en-us/library/ff743760(v=vs.94).aspx