1438

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?

Edric
  • 18,215
  • 11
  • 68
  • 81
Naga Kiran
  • 8,006
  • 5
  • 39
  • 49
  • 169
    your examples don't actually work the way you think they do: http://jsfiddle.net/edelman/WDNVk/1/ – Jason Dec 03 '10 at 17:46
  • 29
    Sorry, passing format strings in toString works in .NET, and it may work in Java, but as Jason pointed out, this doesn't actually work in Javascript. – Joshua Carmody Mar 08 '11 at 20:17
  • 15
    Folks remember - questions, no matter how canonical, *need to remain questions*. Please refrain from any edit that turns this question into an answer, refine and maintain the _answers_ instead. Thanks :) – Tim Post Nov 07 '13 at 10:11
  • 2
    I used the code in this link http://msdn.microsoft.com/en-us/library/ie/ff743760(v=vs.94).aspx -- (date.toLocaleDateString("en-US")); – Khaled Annajar May 25 '14 at 16:52
  • If future visitors to this page are confused by how most of the answers relate to the question, I suggest reading the [question revisions](http://stackoverflow.com/posts/1056728/revisions), especially (if different from above) [revision 15](http://stackoverflow.com/revisions/1056728/15) @[Eric Muyser](http://stackoverflow.com/users/119301) - I for one was confused by the lack of the invalid Date#toString usage. – user66001 Jan 14 '15 at 19:25
  • http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – Jeff Axelrod Aug 31 '16 at 14:35
  • While most of the answers are not really answers ("use library X" does not, of itself, help with documentation on formatting a date), it is quite reasonable to ask where ECMA-262 provides information on a specific task. That is what the answers should have addressed before mentioning other resources. It's difficult to see how any question relating to ECMA-262 can not link to an offsite resource since the specification is kept offsite. – RobG May 01 '18 at 22:42
  • I think that now the [EcmaScript Internationalization API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) should be used to answer this question. Something like that: `let formattedDate = new Intl.DateTimeFormat('en-US').format(XMas95)` It is currently the best solution. – Moisés Márquez Nov 30 '18 at 16:33

36 Answers36

1090

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);
Claies
  • 21,481
  • 3
  • 49
  • 75
Haim Evgi
  • 114,996
  • 43
  • 205
  • 218
  • 29
    Both of these sites have restrictive licenses. So if you use the code (without permission), you'll be in violation. Momentjs (http://stackoverflow.com/a/10119138/278976) looks like a way better option and is MIT license. – Homer6 May 24 '12 at 00:00
  • 1
    @McKay the question specifically asked about string formats, a non-standard JS feature – peller Jun 07 '12 at 02:18
  • 4
    @peller This answer answers the question "How do I format dates in javascript?" which is effectively the title of the question. In the body of the question he is quite mislead. And, to your point, this answer does not talk about string formatting using random non-standard or not mentioned libraries. But that part of the question was asked incorrectly, as the #1 comment on the question points out. So, this answers the real question, but not the format strings that don't actually exist. – McKay Jun 07 '12 at 14:01
  • 3
    @McKay; that wasn't the question. I think you're either misunderstanding what the peller is asking or being obtuse in your reasoning. – codeinthehole Jul 16 '12 at 16:34
  • 10
    @codeinthehole "Formatting dates in Javascript" is the question. "until now I was under the impression that JavaScript doesn't have a built-in API to format a date object into a string." but then talks about the behavior, that I believe he thinks is native in javascript. Without knowing which library he mistakenly references, I think the best guess is that he's asking the question, "How do I format dates in javascript?" and I don't think I'm taking wild leaps. – McKay Jul 16 '12 at 19:24
  • @codeinthehole if peller is referring to "non-standard js" implying that some browsers support such a feature, I'm not aware of any browsers supporting such a feature. I just tried it on Chrome, IE, FF, and Safari. Maybe Opera supports it? – McKay Jul 16 '12 at 19:29
  • 2
    @mcKay; Hi, thanks for explaining your reasoning. I think the person who submitted the question is asking where he/she can find information about the various date formatting strings that are syntactically correct. It seems the poster is aware of _how_ to format dates - but isn't aware of how the syntax for the formatting strings is derived. – codeinthehole Jul 24 '12 at 13:53
  • 1
    @McKay specifically, the toString() signature taking a format string argument was a FF innovation, IIRC, and not standard JS. Firefox does not currently support this, I don't think any browser does anymore, which is why I felt it was important two years ago to discourage the user from doing this. While JS libs may be the solution for this user, the question was very specific to the Date object in core JS and browser behavior in 2009. – peller Sep 04 '12 at 21:59
  • @torvin even then you have to click through each page laboriously to go through all examples. – Kamal Reddy Mar 19 '13 at 12:35
  • 5
    MM mean 01-12, not 1-12: 2013-04-17 => OK 2013-4-17 => BAD – Adrian Maire Apr 17 '13 at 09:10
  • 1
    Thanks a lot.I was wondering for the past 2 hours why I am getting difference of 1 for d.getMonth() – Arun Unnikrishnan Sep 12 '13 at 04:17
  • No part of this site can be duplicated in any form without written permission from the Webmaster – Legionar Nov 25 '13 at 10:29
  • 2
    important: don't forget to do `d.getMonth() + 1` because some moron programmer once decided dates should be zero based – Simon_Weaver Jul 20 '14 at 06:23
  • I prefer the answer by chx007 referencing Moment.js, as it alleviates @Homer6 's concern about restrictive licenses and doing "technically-illegal" things. – Nathan Apr 02 '20 at 05:36
  • 1
    @nathan No one can claim ownership of simple JavaScript statements. It is not technically illegal. – Steve Carey May 04 '21 at 05:08
682

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)

Philipp Kyeck
  • 16,652
  • 15
  • 72
  • 105
chx007
  • 7,249
  • 1
  • 13
  • 9
  • 7
    This also provides a decorator pattern around the Date object instead of monkey punching the core object, so you're less likely to get conflicts down the road. – Gabe Martin-Dempesy Nov 26 '12 at 18:20
  • 4
    I don't think I've ever come across a library in *any* programming language/environment that serves its purpose so perfectly. Also the docs are extensive and really, really good. Really happy to have found this because dates have been a pain to deal with in the past (though Datejs improved the situation somewhat for me). – Zac Seth Mar 13 '13 at 11:43
  • FWIW, moment.min.js is currently at 14.3 KB. – WynandB Apr 03 '13 at 02:23
  • I replaced Datejs with Moment recently. – Tien Do Apr 26 '13 at 02:48
  • 122
    Please stop abusing the word "lightweight". Even 5kb is ridiculously large for such functionality, and as per today that size has increased to 19kb. – user123444555621 Sep 26 '13 at 06:22
  • 1
    As of this comment the moment.min.js file is at 8.9kb – Greg M. Krsak Oct 31 '13 at 15:28
  • 27
    @Pumbaa80 I disagree that "Even 5kb is ridiculously large for such functionality". [Have you seen the docs?](http://momentjs.com/docs/) It is an extremely useful library for dealing with dates in JS. I understand having a library greater than a couple of KBs for a single use of a basic format like "D/M/Y" can be a little overkill however differences of a few KBs is becoming negligible for then the ease of use the library provides. Maintainable code is a good thing for the sake of a few KBs. If it was +100KB minified, I would however agree. – Turnerj Dec 04 '13 at 01:26
  • 2
    "Lightweight" is relative. Even 5KB wasn't lightweight by 1984's standards. :/ – Mr. Lance E Sloan Dec 04 '13 at 18:27
  • 15
    @Tumerj arguing that it is useful does nothing to address the concern of being lightweight. The two are not related. – JoshJordan May 30 '14 at 19:58
  • 9
    You can't make a jet plane more lightweight by removing the engine because it then becomes a glider and not a jet. Lightweight means something has only necessary functionality to perform a specified function. Ergo, this is a lightweight solution. – Bon Jun 25 '14 at 00:47
  • For those who are wondering about moment.js, see this simple fiddle: http://jsfiddle.net/t5MuD/ it only shows a fraction of the power of moment. You can read a whole lot more on http://momentjs.com/docs/ – Sudhanshu Mishra Jul 07 '14 at 14:41
  • 2
    @Pumbaa80 File size is irrelevant. While 'use datejs' is a solution to the OP's problem it does not actually answer the question. OP has learned nothing which is unfortunate because the actual answer is incredibly simple. SO is lousy with 'use jQuery' style answers. – Shawn Whinnery Jul 25 '14 at 22:38
  • Moment.js is by no means lightweight. In 2016, people were complaining about [tens/hundreds of kilobytes](https://github.com/moment/moment/issues/3376#issuecomment-260949065) added by the library, and a number of date picker libraries take pride in [*not*](https://github.com/flatpickr/flatpickr) depending on Moment.js. – Dan Dascalescu Aug 15 '18 at 03:15
  • This should be the accepted answer. Rather, SO should probably get rid of the "accept answer" functionality altogether – Nathan Apr 02 '20 at 05:10
428

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
casid
  • 4,353
  • 1
  • 11
  • 2
  • how to tell it to use local time or Zulu? – Ustaman Sangat Mar 02 '12 at 16:14
  • 7
    i prefer use this solution able to get the time without any library : new Date().toTimeString().match( /^([0-9]{2}:[0-9]{2}:[0-9]{2})/ )[0] FYI – markcial May 31 '12 at 08:05
  • is there a way to do this. $.datepicker.formatDate('yy-mm-dd', new Date("txtAdvDate".Val()); or some thing like that – Pomster Jun 01 '12 at 13:09
  • @Pomster - what would make you think the string "txtAdvDate" would have a val method on it? Do you mean $('#txtAdvDate').val()? Assuming it fits one of the constructors (see here http://www.w3schools.com/jsref/jsref_obj_date.asp) then that would work just fine. – vbullinger Sep 27 '12 at 15:46
  • @Pomster - try using this: document.getElementById(id).value = $.datepicker.formatDate('yy-mm-dd', new Date()); – mrrsb Dec 10 '12 at 09:16
  • URL with an anchor to the relevant part of that page: http://api.jqueryui.com/datepicker/#utility-formatDate – Michael Scheper May 13 '14 at 01:23
  • The problem with datepicker (which I am currently using) is I want the input box to show dd-mm-yyyy but the value passed in the form to be yyyy-mm-dd. Don't think it can be done without manipulation. – khany Jul 11 '14 at 10:34
225

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
Klik
  • 1,642
  • 1
  • 19
  • 37
Adrian Maire
  • 11,506
  • 8
  • 34
  • 72
  • 10
    It should be accepted answer, because it gives the required format (01-01-2000, not 1-1-2000) – Danubian Sailor Apr 12 '13 at 13:56
  • 6
    new Date().toISOString().slice(0,10) // "2015-04-27" – image72 Apr 27 '15 at 03:08
  • 2
    Would be very helpful not to have the example with 11th of September so it would be clear at which position is day and month represented. – Karl Adler Aug 11 '17 at 08:22
  • 1
    thanks for adding the links to the source (: - see also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString – Sandra Feb 25 '19 at 16:55
220

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.

user123444555621
  • 130,762
  • 25
  • 104
  • 122
Scott Offen
  • 5,943
  • 3
  • 19
  • 22
  • 26
    MDN is also a great reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – Cypher Oct 16 '13 at 23:25
  • 2
    My answer attempted to address this question also. I do believe that Firefox or Mozilla browsers once provided a Date.toString() method which took such a formatting string. Unfortunately, I can find no trace of the old documentation. It's no longer part of the standard and doesn't seem to be supported anywhere anymore, even in Firefox. – peller Oct 18 '13 at 00:15
125

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

http://tools.ietf.org/html/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

http://tools.ietf.org/html/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

JJJ
  • 31,545
  • 20
  • 84
  • 99
Sg'te'gmuj
  • 151
  • 1
  • 2
  • 5
91

Make sure you checkout Datejs when dealing with dates in JavaScript. It's quite impressive and well documented as you can see in case of the toString function.

EDIT: Tyler Forsythe points out, that datejs is outdated. I use it in my current project and hadn't any trouble with it, however you should be aware of this and consider alternatives.

Tim Büthe
  • 58,799
  • 16
  • 82
  • 126
  • 1
    This is a fantastic library. I have created a version of my own, but I have scrapped that project in favor of using this. Thanks for the link!!!! (can you tell I am excited) – John Livermore Jul 21 '11 at 04:03
  • 1
    +1 for using a already existing good lib, instead of half baked solution – Anurag Uniyal Sep 27 '11 at 16:18
  • 2
    I couldn't find a way to feed datejs with milliseconds to create a date. Like so: var dateTime = new Date(); dateTime.setTime(milliseconds); – Arne Evertsson Nov 30 '11 at 12:58
  • 1
    I can't believe such a popular library doesnt have the ability to create a date using milliseconds/seconds since the epoch. – you786 Jul 27 '12 at 00:10
  • Keep in mind, when using the cool date adding / "next thursday" type functions, always first convert to UTC, then add/subtract dates, then convert back to local time. – ingredient_15939 Sep 14 '12 at 14:58
  • Here's a list of formatting strings that seem to work with Datejs: http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm I didn't test all of them, but the few that I've used worked fine. – Phil Gran Sep 20 '12 at 16:40
  • 14
    25k? Just for dates? Ouch. – Ben Lesh Jan 08 '13 at 19:53
  • 13
    Datejs is an outdated library that hasn't seen active development in ~5 years. Their source is on Github and Google Code and both have last updated dates of 2008 (it's 2013). For the sake of your sanity, go with XDate or Moment.js. – Tyler Forsythe Jul 24 '13 at 21:51
  • 3
    @TylerForsythe I added a hint / warning about that. – Tim Büthe Jul 25 '13 at 08:30
  • Another highly voted answer that doesn't answer the question. – RobG Aug 26 '14 at 07:00
  • @RobG I thought this was a case of the [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Tim Büthe Aug 26 '14 at 09:15
  • 1
    As of September 2018, the latest commit was a723995 *on Jul 4, 2017* – Ricardo Sep 05 '18 at 23:17
70

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"));
gongzhitaao
  • 6,073
  • 3
  • 32
  • 44
  • Enhanced it a bit for my purposes to support AM/PM - see below – Michael Angstadt Jul 30 '13 at 15:42
  • @WHK But I still like [momentjs](http://momentjs.com/) more :D – gongzhitaao Jun 12 '14 at 14:42
  • Have problem when capture month: new Date((new Date()).format('yyyy-MM-dd')) return May but now is Jun :-/ whoto use timezone in parse string? – e-info128 Jun 12 '14 at 15:08
  • console.log(new Date('2014-06-12')); -> Jun || console.log(new Date('2014-06-01')); -> May ??? – e-info128 Jun 12 '14 at 15:11
  • 1
    @WHK This is actually a very primitive date parser. Just in case you don't have to mess with date too much. If you really need to cope with various formats of dates, I would recommend a standalone library like momentjs. :D – gongzhitaao Jun 12 '14 at 15:40
  • 1
    @WHK For `console.log(new Date('2014-06-01')) -> May` I think it has something to do with the timezone :D – gongzhitaao Jun 12 '14 at 15:42
36

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 dojo.date.locale.

peller
  • 4,435
  • 16
  • 20
  • 5
    Attempting to actually answer the question won't get you many votes. Just nominate a popular library and see your score fly!! – RobG Aug 26 '14 at 07:02
31

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]; }],
    y:['getFullYear'],
    H:['getHours',function(v) { return zeroPad(v)}],
    M:['getMinutes',function(v) { return zeroPad(v)}],
    S:['getSeconds',function(v) { return zeroPad(v)}],
    i:['toISOString']
  };

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

http://snipplr.com/view/66968.82825/

Lyndon S
  • 575
  • 6
  • 6
  • 4
    I like this class but think it should be a "static" class. No need to instantiate it more than once. (should not need `new DateFmt()`) – Cheeso Jan 16 '13 at 00:59
  • 1
    Cheeso: What if I want to format 10 different dates on a page 3 different ways, each? In that case it would be useful to have three instances of this formatter. That's a perfectly valid usecase that this would preclude. The OP designed this correctly. Also specifying a format at construction time saves code duplication of specifying a format every time you need it formatted a certain way. – hsanders Jun 03 '14 at 20:12
29

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"
John Williams
  • 9,282
  • 4
  • 33
  • 44
21

DateJS is certainly full-featured, but I'd recommend this MUCH simpler lib (JavaScript Date Format) which I prefer simply because it's only 120 lines or so.

Eric Wendelin
  • 39,122
  • 8
  • 59
  • 87
  • Source code references in linked article are dead, but fortunately someone put it on Github: https://github.com/rvanbaalen/date-steroids – Geert Oct 30 '14 at 09:04
18

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"));
Ollie Bennett
  • 4,064
  • 1
  • 17
  • 25
  • 2
    replace operations are not really efficient, so it's a better practise to prevent it. – mrzmyr Oct 09 '12 at 15:43
  • what if I write, what is going to happen? console.log("The date is: " + dateFormat(new Date(), "DD/MM/YY")); – hakan Nov 11 '13 at 13:49
  • 1
    This will print the text "The date is: 12/11/YY", because the above does not handle 2-digit dates. If you needed this, you could add the following immediately before the return statement: `format = format.replace("YY", (""+date.getFullYear()).substring(2));`. This is getting ugly though - you probably want to go down the RegEx route or similar instead. – Ollie Bennett Nov 12 '13 at 10:12
  • 1
    @mrzmyr Do you really think that formatting dates will be a performance bottleneck? Come on. – doug65536 Dec 27 '13 at 10:30
11

Here's a function I use a lot. The result is yyyy-mm-dd hh:mm:ss.nnn.

function date_and_time() {
    var date = new Date();
    //zero-pad a single zero if needed
    var zp = function (val){
        return (val <= 9 ? '0' + val : '' + val);
    }

    //zero-pad up to two zeroes if needed
    var zp2 = function(val){
        return val <= 99? (val <=9? '00' + val : '0' + val) : ('' + val ) ;
    }

    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    var h = date.getHours();
    var min = date.getMinutes();
    var s = date.getSeconds();
    var ms = date.getMilliseconds();
    return '' + y + '-' + zp(m) + '-' + zp(d) + ' ' + zp(h) + ':' + zp(min) + ':' + zp(s) + '.' + zp2(ms);
}
Carl
  • 39,407
  • 10
  • 74
  • 99
  • 1
    good answer, but I think you should change the zp2 function as: var zp2 = function(val) { return val <= 9 ? '00' + val : (val <= 99 ? '0' + val : '' + val); } – user218867 Dec 23 '13 at 02:52
  • 1
    there is an exception, when the value of ms part is 0, it's not the same, in your function the result is '00', but not '000'. – user218867 Dec 25 '13 at 14:40
9

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

NOTE:

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

CODE

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

USE

var now = new Date;
console.log(now.format());
// 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
Rudolf Gröhling
  • 3,195
  • 2
  • 21
  • 35
8

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;
}
Michael Angstadt
  • 850
  • 10
  • 16
8

All browsers

The most reliable way to format a date with the source format you're using, is to apply the following steps :

  1. Use new Date() to create a Date object
  2. Use .getDate(), .getMonth() and .getFullYear() to get respectively the day, month and year
  3. Paste the pieces together according to your target format

Example :

var date = '2015-11-09T10:46:15.097Z';

function format(input) {
    var date = new Date(input);
    return [
       ("0" + date.getDate()).slice(-2),
       ("0" + (date.getMonth()+1)).slice(-2),
       date.getFullYear()
    ].join('/');
}

document.body.innerHTML = format(date); // OUTPUT : 09/11/2015

(See also this Fiddle).


Modern browsers only

You can also use the built-in .toLocaleDateString method to do the formatting for you. You just need pass along the proper locale and options to match the right format, which unfortunately is only supported by modern browsers (*) :

var date = '2015-11-09T10:46:15.097Z';

function format(input) {
    return new Date(input).toLocaleDateString('en-GB', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
}

document.body.innerHTML = format(date); // OUTPUT : 09/11/2015

(See also this Fiddle).


(*) According to the MDN, "Modern browsers" means Chrome 24+, Firefox 29+, IE11, Edge12+, Opera 15+ & Safari nightly build

John Slegers
  • 38,420
  • 17
  • 182
  • 152
7

I was unable to find any definitive documentation on valid date formats so I wrote my own test to see what is supported in various browsers.

http://blarg.co.uk/blog/javascript-date-formats

My results concluded the following formats are valid in all browsers that I tested (examples use the date "9th August 2013"):

[Full Year]/[Month]/[Date number] - Month can be either the number with or without a leading zero or the month name in short or long format, and date number can be with or without a leading zero.

  • 2013/08/09
  • 2013/08/9
  • 2013/8/09
  • 2013/8/9
  • 2013/August/09
  • 2013/August/9
  • 2013/Aug/09
  • 2013/Aug/9

[Month]/[Full Year]/[Date Number] - Month can be either the number with or without a leading zero or the month name in short or long format, and date number can be with or without a leading zero.

  • 08/2013/09
  • 08/2013/9
  • 8/2013/09
  • 8/2013/9
  • August/2013/09
  • August/2013/9
  • Aug/2013/09
  • Aug/2013/9

Any combination of [Full Year], [Month Name] and [Date Number] separated by spaces - Month name can be in either short or long format, and date number can be with or without a leading zero.

  • 2013 August 09
  • August 2013 09
  • 09 August 2013
  • 2013 Aug 09
  • Aug 9 2013
  • 2013 9 Aug
  • etc...

Also valid in "modern browsers" (or in other words all browsers except IE9 and below)

[Full Year]-[Month Number]-[Date Number] - Month and Date Number must include leading zeros (this is the format that the MySQL Date type uses)

  • 2013-08-09

Using month names:
Interestingly, when using month names I discovered that only the first 3 characters of the month name are ever used so all the of the following are perfectly valid:

new Date('9 August 2013');
new Date('9 Aug 2013');
new Date('9 Augu 2013');
new Date('9 Augustagfsdgsd 2013');
Pete Newnham
  • 221
  • 5
  • 7
6

The library sugar.js has some great functionality for working with dates in JavaScript. And it is very well documented.

Sugar gives the Date class much love starting with the Date.create method which can understand dates in just about any format in 15 major languages, including relative formats like "1 hour ago". Dates can also be output in any format or language using an easy to understand syntax, with shortcuts to commonly used date formats. Complex date comparison is also possible with methods like is, which understand any format and apply built in precision.

A few examples:

Date.create('July 4, 1776')  -> July 4, 1776
Date.create(-446806800000)   -> November 5, 1955
Date.create(1776, 6, 4)      -> July 4, 1776
Date.create('1776年07月04日', 'ja') -> July 4, 1776
Date.utc.create('July 4, 1776', 'en')  -> July 4, 1776

Date.create().format('{Weekday} {d} {Month}, {yyyy}')    -> Monday July 4, 2003
Date.create().format('{hh}:{mm}')                        -> 15:57
Date.create().format('{12hr}:{mm}{tt}')                  -> 3:57pm
Date.create().format(Date.ISO8601_DATETIME)              -> 2011-07-05 12:24:55.528Z

Date.create().is('the 7th of June') -> false
Date.create().addMonths(2); ->"Sunday, June 15, 2014 13:39"
andersh
  • 6,839
  • 4
  • 36
  • 28
6

Example code:

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

Output:

"13:45:20"

Nery Jr
  • 3,421
  • 23
  • 22
  • 2
    worth noting with toISOString(); it outputs UTC. So if `new Date();// = Fri Nov 22 2013 17:48:22 GMT+0100`, the output with the above code will be `"16:48:22"` – Tewr Nov 22 '13 at 16:50
6

Formatting and especially parsing dates in JavaScript can be a bit of a headache. Not all browsers handle dates in the same way. So while it's useful to know the base methods, its more practical to use a helper library.

The XDate javascript library by Adam Shaw has been around since mid-2011 and is still under active development. It has fantastic documentation, a great API, formatting, tries to remain backwards-compatible and even supports localized strings.

Link to changing the locale strings: https://gist.github.com/1221376

Peter O.
  • 28,965
  • 14
  • 72
  • 87
Sam Lown
  • 104
  • 1
  • 3
3

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.

Jim Davis
  • 1,190
  • 5
  • 11
  • 1
    I guess the new URL is http://depressedpress.com/javascript-extensions/dp_dateextensions/ – torvin May 25 '11 at 11:07
2

If you want to show only time with two digits, this may helps you:

var now = new Date();
var cHour = now.getHours();
var cMinuts = now.getMinutes();
var cSeconds = now.getSeconds();

var outStr = (cHour <= 0 ? ('0' + cHour) : cHour) + ':' + (cMinuts <= 9 ? ('0' + cMinuts) : cMinuts) + ':' + (cSeconds <= 9 ? '0' + cSeconds : cSeconds);
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Usman Younas
  • 1,203
  • 13
  • 18
2

use this functions

toTimeString() and toLocaleDateString()

refer below link for more details https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

nidhin
  • 349
  • 1
  • 3
  • 13
1

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.

Example:

var sdf = new JsSimpleDateFormat("EEEE, MMMM dd, yyyy");
var formattedString = sdf.format(new Date());
var dateObject = sdf.parse("Monday, June 29, 2009");
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Peter
  • 19
  • 1
1

The answer is "nowhere" since the date formatting is proprietary functionality. I don't think the toString functions are intended to conform to a specific format. e.g. in the ECMAScript 5.1 spec (http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, 2/8/2013, page 173), the toString function is documented as follows:

"The contents of the String are implementation-dependent"

Functions such as the samples below could be used to accomplish formatting fairly easily.

function pad(toPad, padWith) {
    return (String(padWith) + String(toPad)).slice(-1 * padWith.length);
}

function dateAsInputValue(toFormat) {
    if(!(toFormat instanceof Date)) return null;
    return toFormat.getFullYear() + "-" + pad(toFormat.getMonth() + 1, "00") + "-" + pad(toFormat.getDate(), "00");
}

function timeAsInputValue(toFormat) {
    if(!(toFormat instanceof Date)) return null;        
    return pad(toFormat.getHours(), "00") + ":" + pad(toFormat.getMinutes(), "00") + ":" + pad(toFormat.getSeconds(), "00");
}
goofballLogic
  • 31,055
  • 8
  • 37
  • 50
1

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:
 * http://man7.org/linux/man-pages/man3/strftime.3.html
 *
 * Day of year (%j) code based on Joe Orost's answer:
 * http://stackoverflow.com/questions/8619879/javascript-calculate-the-day-of-the-year-1-366
 *
 * Week number (%V) code based on Taco van den Broek's prototype:
 * http://techblog.procurios.nl/k/news/view/33796/14863/calculate-iso-8601-week-and-year-in-javascript.html
 */
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: https://github.com/thdoan/strftime

thdoan
  • 15,024
  • 1
  • 46
  • 40
0

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();
d1.toString('yyyy-MM-dd');      
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Sebastian Viereck
  • 4,233
  • 36
  • 46
0

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

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 php.net

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.

Cloudranger
  • 1,209
  • 10
  • 6
0

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")
ProVega
  • 5,543
  • 2
  • 34
  • 34
0

See dtmFRM.js. If you are familiar with C#'s custom date and time format string, this library should do the exact same thing.

DEMO:

var format = new dtmFRM();
var now = new Date().getTime();

$('#s2').append(format.ToString(now,"This month is : MMMM") + "</br>");
$('#s2').append(format.ToString(now,"Year is  : y or yyyy or yy") + "</br>");
$('#s2').append(format.ToString(now,"mm/yyyy/dd") + "</br>");
$('#s2').append(format.ToString(now,"dddd, MM yyyy ") + "</br>");
$('#s2').append(format.ToString(now,"Time is : hh:mm:ss ampm") + "</br>");
$('#s2').append(format.ToString(now,"HH:mm") + "</br>");
$('#s2').append(format.ToString(now,"[ddd,MMM,d,dddd]") + "</br></br>");

now = '11/11/2011 10:15:12' ;

$('#s2').append(format.ToString(now,"MM/dd/yyyy hh:mm:ss ampm") + "</br></br>");

now = '40/23/2012'
$('#s2').append(format.ToString(now,"Year is  : y or yyyy or yy") + "</br></br>");
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mina Gabriel
  • 17,138
  • 23
  • 89
  • 118
0

d = Date.now();
d = new Date(d);
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");

console.log(d);
Cris
  • 2,124
  • 18
  • 19
0

the lazy solution is to use Date.toLocaleString with the right region code

to get a list of matching regions you can run

#!/bin/bash

[ -f bcp47.json ] || \
wget https://raw.githubusercontent.com/pculture/bcp47-json/master/bcp47.json

grep 'tag" : ' bcp47.json | cut -d'"' -f4 >codes.txt

js=$(cat <<'EOF'
const fs = require('fs');
const d = new Date(2020, 11, 12, 20, 00, 00);
fs.readFileSync('codes.txt', 'utf8')
.split('\n')
.forEach(code => {
  try {
    console.log(code+' '+d.toLocaleString(code))
  }
  catch (e) { console.log(code+' '+e.message) }
});
EOF
)

# print THE LIST of civilized countries
echo "$js" | node - | grep '2020-12-12 20:00:00'

and here is .... THE LIST

af ce eo gv ha ku kw ky lt mg rw se sn sv xh zu 
ksh mgo sah wae AF KW KY LT MG RW SE SN SV

sample use:

(new Date()).toLocaleString('af')

// -> '2020-12-21 11:50:15'

: )

(note. this MAY not be portable.)

Mila Nautikus
  • 684
  • 6
  • 12
-1

Although JavaScript gives you many great ways of formatting and calculations, I prefer using the Moment.js (momentjs.com) library during application development as it's very intuitive and saves a lot of time.

Nonetheless, I suggest everyone to learn about the basic JavaScript API too for a better understanding.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gaurav Karwal
  • 116
  • 1
  • 10
-1

We can do it manually, its pretty straight and simple.

var today = new Date();
    
    alert("today :"+today);
    
    var dd = today.getDate();
    alert("dd :"+dd);
    
    var mm = today.getMonth()+1; //January is 0!
    alert("mm :"+mm);
    
    var yyyy = today.getFullYear();
    
    alert("yyyy :"+yyyy);
    
    
    var hh = today.getHours();
    
    alert("hh :"+hh);
    
    var min = today.getMinutes();
    
   alert("min :"+min);
   
   var ss = today.getSeconds();
   
   alert("ss :"+ss);

    if(dd<10) {
        dd='0'+dd
    } 

    if(mm<10) {
        mm='0'+mm
    } 

  //  today = mm+'/'+dd+'/'+yyyy;
    // if you want / instead - then add /
  
  
  today = yyyy + "-" + mm + "-" + dd + " " + hh + ":" + mm + ":" + ss;
     today = yyyy + "/" + mm + "/" + dd + " " + hh + ":" + mm + ":" + ss;
     // use according to your choice 
Varun
  • 5,501
  • 18
  • 69
  • 107
-1

The specific answer to this question is found in these two lines below:

//pull the last two digits of the year
console.log(new Date().getFullYear().toString().substr(2,2));

Formatting Full Date Time Example (MMddyy): jsFiddle

JavaScript:

    //A function for formatting a date to MMddyy
function formatDate(d)
{
    //get the month
    var month = d.getMonth();
    //get the day
    var day = d.getDate();
    //get the year
    var year = d.getFullYear();
    
    //pull the last two digits of the year
    year = year.toString().substr(2,2);
    
    //increment month by 1 since it is 0 indexed
    month = month + 1;
    //converts month to a string
    month = month + "";

    //if month is 1-9 pad right with a 0 for two digits
    if (month.length == 1)
    {
        month = "0" + month;
    }

    //convert day to string
    day = day + "";

    //if day is between 1-9 pad right with a 0 for two digits
    if (day.length == 1)
    {
        day = "0" + day;
    }

    //return the string "MMddyy"
    return month + day + year;
}

var d = new Date();
console.log(formatDate(d));
abc123
  • 16,261
  • 6
  • 46
  • 76