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

1,527,656

Solution 1

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

Solution 2

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)

Solution 3

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.

Solution 4

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

Solution 5

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.

Share:
1,527,656
Naga Kiran
Author by

Naga Kiran

Updated on April 12, 2022

Comments

  • Naga Kiran
    Naga Kiran about 2 years

    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?

    • Ricardo Gomes
      Ricardo Gomes over 13 years
      your examples don't actually work the way you think they do: jsfiddle.net/edelman/WDNVk/1
    • Guilherme David da Costa
      Guilherme David da Costa about 13 years
      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.
    • Tim Post
      Tim Post over 10 years
      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 :)
    • Khaled Annajar
      Khaled Annajar almost 10 years
      I used the code in this link msdn.microsoft.com/en-us/library/ie/ff743760(v=vs.94).aspx -- (date.toLocaleDateString("en-US"));
    • user66001
      user66001 over 9 years
      If future visitors to this page are confused by how most of the answers relate to the question, I suggest reading the question revisions, especially (if different from above) revision 15 @Eric Muyser - I for one was confused by the lack of the invalid Date#toString usage.
    • Jeff Axelrod
      Jeff Axelrod over 7 years
    • RobG
      RobG almost 6 years
      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.
    • Moisés Márquez
      Moisés Márquez over 5 years
      I think that now the EcmaScript Internationalization API 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.
  • torvin
    torvin almost 13 years
  • John Livermore
    John Livermore almost 13 years
    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)
  • Nandhini
    Nandhini over 12 years
    +1 for using a already existing good lib, instead of half baked solution
  • Arne Evertsson
    Arne Evertsson over 12 years
    I couldn't find a way to feed datejs with milliseconds to create a date. Like so: var dateTime = new Date(); dateTime.setTime(milliseconds);
  • Ustaman Sangat
    Ustaman Sangat about 12 years
    how to tell it to use local time or Zulu?
  • Homer6
    Homer6 almost 12 years
    Both of these sites have restrictive licenses. So if you use the code (without permission), you'll be in violation. Momentjs (stackoverflow.com/a/10119138/278976) looks like a way better option and is MIT license.
  • markcial
    markcial almost 12 years
    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
  • Pomster
    Pomster almost 12 years
    is there a way to do this. $.datepicker.formatDate('yy-mm-dd', new Date("txtAdvDate".Val()); or some thing like that
  • peller
    peller almost 12 years
    @McKay the question specifically asked about string formats, a non-standard JS feature
  • McKay
    McKay almost 12 years
    @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.
  • user3264001
    user3264001 almost 12 years
    @McKay; that wasn't the question. I think you're either misunderstanding what the peller is asking or being obtuse in your reasoning.
  • McKay
    McKay almost 12 years
    @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
    McKay almost 12 years
    @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?
  • user3264001
    user3264001 almost 12 years
    @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.
  • you786
    you786 almost 12 years
    I can't believe such a popular library doesnt have the ability to create a date using milliseconds/seconds since the epoch.
  • peller
    peller over 11 years
    @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.
  • ingredient_15939
    ingredient_15939 over 11 years
    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.
  • Phil Gran
    Phil Gran over 11 years
    Here's a list of formatting strings that seem to work with Datejs: 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.
  • vbullinger
    vbullinger over 11 years
    @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 w3schools.com/jsref/jsref_obj_date.asp) then that would work just fine.
  • e382df99a7950919789725ceeec126
    e382df99a7950919789725ceeec126 over 11 years
    replace operations are not really efficient, so it's a better practise to prevent it.
  • Gabe Martin-Dempesy
    Gabe Martin-Dempesy over 11 years
    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.
  • mrrsb
    mrrsb over 11 years
    @Pomster - try using this: document.getElementById(id).value = $.datepicker.formatDate('yy-mm-dd', new Date());
  • Ben Lesh
    Ben Lesh over 11 years
    25k? Just for dates? Ouch.
  • Cheeso
    Cheeso over 11 years
    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())
  • Zac Seth
    Zac Seth about 11 years
    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).
  • Kamal Reddy
    Kamal Reddy about 11 years
    @torvin even then you have to click through each page laboriously to go through all examples.
  • WynandB
    WynandB about 11 years
    FWIW, moment.min.js is currently at 14.3 KB.
  • Danubian Sailor
    Danubian Sailor about 11 years
    It should be accepted answer, because it gives the required format (01-01-2000, not 1-1-2000)
  • Adrian Maire
    Adrian Maire about 11 years
    MM mean 01-12, not 1-12: 2013-04-17 => OK 2013-4-17 => BAD
  • Tien Do
    Tien Do about 11 years
    I replaced Datejs with Moment recently.
  • Sebastian Viereck
    Sebastian Viereck almost 11 years
    you need the script linked "JavaScript Date Format" linked above
  • Tyler Forsythe
    Tyler Forsythe almost 11 years
    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.
  • Tim Büthe
    Tim Büthe almost 11 years
    @TylerForsythe I added a hint / warning about that.
  • Michael Angstadt
    Michael Angstadt over 10 years
    Enhanced it a bit for my purposes to support AM/PM - see below
  • Adrian Maire
    Adrian Maire over 10 years
    Very good solution! var a = new Date(); a.format('yyyy-MM-d'); //Return 2013-08-16.
  • Arun Unnikrishnan
    Arun Unnikrishnan over 10 years
    Thanks a lot.I was wondering for the past 2 hours why I am getting difference of 1 for d.getMonth()
  • Ansel Halliburton
    Ansel Halliburton over 10 years
    Please stop abusing the word "lightweight". Even 5kb is ridiculously large for such functionality, and as per today that size has increased to 19kb.
  • Iftah
    Iftah over 10 years
    is this cross browser? and cross locale?
  • C B
    C B over 10 years
    Yes. Shows time in your (browser user) local time zone.
  • Cypher
    Cypher over 10 years
  • peller
    peller over 10 years
    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.
  • Greg M. Krsak
    Greg M. Krsak over 10 years
    As of this comment the moment.min.js file is at 8.9kb
  • hakan
    hakan over 10 years
    what if I write, what is going to happen? console.log("The date is: " + dateFormat(new Date(), "DD/MM/YY"));
  • Ollie Bennett
    Ollie Bennett over 10 years
    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.
  • Tewr
    Tewr over 10 years
    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"
  • Legionar
    Legionar over 10 years
    No part of this site can be duplicated in any form without written permission from the Webmaster
  • Turnerj
    Turnerj over 10 years
    @Pumbaa80 I disagree that "Even 5kb is ridiculously large for such functionality". Have you seen the 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.
  • Mr. Lance E Sloan
    Mr. Lance E Sloan over 10 years
    "Lightweight" is relative. Even 5KB wasn't lightweight by 1984's standards. :/
  • Eric
    Eric over 10 years
    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); }
  • Eric
    Eric over 10 years
    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'.
  • doug65536
    doug65536 over 10 years
    @mrzmyr Do you really think that formatting dates will be a performance bottleneck? Come on.
  • Michael Scheper
    Michael Scheper almost 10 years
    URL with an anchor to the relevant part of that page: api.jqueryui.com/datepicker/#utility-formatDate
  • JoshJordan
    JoshJordan almost 10 years
    @Tumerj arguing that it is useful does nothing to address the concern of being lightweight. The two are not related.
  • hsanders
    hsanders almost 10 years
    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.
  • gongzhitaao
    gongzhitaao almost 10 years
    @WHK But I still like momentjs more :D
  • e-info128
    e-info128 almost 10 years
    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
    e-info128 almost 10 years
    console.log(new Date('2014-06-12')); -> Jun || console.log(new Date('2014-06-01')); -> May ???
  • gongzhitaao
    gongzhitaao almost 10 years
    @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
    gongzhitaao almost 10 years
    @WHK For console.log(new Date('2014-06-01')) -> May I think it has something to do with the timezone :D
  • Bon
    Bon almost 10 years
    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.
  • Sudhanshu Mishra
    Sudhanshu Mishra almost 10 years
    For those who are wondering about moment.js, see this simple fiddle: jsfiddle.net/t5MuD it only shows a fraction of the power of moment. You can read a whole lot more on momentjs.com/docs
  • khany
    khany almost 10 years
    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.
  • aruno
    aruno almost 10 years
    important: don't forget to do d.getMonth() + 1 because some moron programmer once decided dates should be zero based
  • Shawn Whinnery
    Shawn Whinnery almost 10 years
    @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.
  • RobG
    RobG over 9 years
    Another highly voted answer that doesn't answer the question.
  • RobG
    RobG over 9 years
    Attempting to actually answer the question won't get you many votes. Just nominate a popular library and see your score fly!!
  • Tim Büthe
    Tim Büthe over 9 years
    @RobG I thought this was a case of the XY Problem
  • Geert
    Geert over 9 years
    Source code references in linked article are dead, but fortunately someone put it on Github: github.com/rvanbaalen/date-steroids
  • N20084753
    N20084753 about 9 years
    this.getMonth(); fails in iOS
  • image72
    image72 about 9 years
    new Date().toISOString().slice(0,10) // "2015-04-27"
  • Ivan Crojach Karačić
    Ivan Crojach Karačić about 8 years
    Just a small comment it's not 'hh + ":" + mm + ":" + ss;' but 'hh + ":" + min + ":" + ss;' :)
  • Karl Adler
    Karl Adler over 6 years
    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.
  • Dan Dascalescu
    Dan Dascalescu over 5 years
    Moment.js is by no means lightweight. In 2016, people were complaining about tens/hundreds of kilobytes added by the library, and a number of date picker libraries take pride in not depending on Moment.js.
  • Dan Dascalescu
    Dan Dascalescu over 5 years
    It's also incredibly bloated.
  • Ricardo
    Ricardo over 5 years
    As of September 2018, the latest commit was a723995 on Jul 4, 2017
  • Sandra
    Sandra about 5 years
  • Nathan
    Nathan about 4 years
    This should be the accepted answer. Rather, SO should probably get rid of the "accept answer" functionality altogether
  • Nathan
    Nathan about 4 years
    I prefer the answer by chx007 referencing Moment.js, as it alleviates @Homer6 's concern about restrictive licenses and doing "technically-illegal" things.
  • Shardul Birje
    Shardul Birje almost 4 years
    Today in 2020, it supports most browsers.
  • Steve Carey
    Steve Carey almost 3 years
    @nathan No one can claim ownership of simple JavaScript statements. It is not technically illegal.