标签云

微信群

扫码加入我们

WeChat QR Code

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 Chromed1.toString('dddd, MMMM ,yyyy')//Returns "Monday, June 29,2009" in Internet Explorer, but not Firefox or ChromeAlso 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?


your examples don't actually work the way you think they do: jsfiddle.net/edelman/WDNVk/1

2019年07月21日04分20秒

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.

2019年07月21日04分20秒

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

2019年07月20日04分20秒

I used the code in this link msdn.microsoft.com/en-us/library/ie/ff743760(v=vs.94).aspx -- (date.toLocaleDateString("en-US"));

2019年07月21日04分20秒

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.

2019年07月20日04分20秒

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.

2019年07月20日04分20秒

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.

2019年07月20日04分20秒

McKay; that wasn't the question.I think you're either misunderstanding what the peller is asking or being obtuse in your reasoning.

2019年07月20日04分20秒

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.

2019年07月20日04分20秒

MM mean 01-12, not 1-12: 2013-04-17 => OK 2013-4-17 => BAD

2019年07月20日04分20秒

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.

2019年07月21日04分20秒

Please stop abusing the word "lightweight". Even 5kb is ridiculously large for such functionality, and as per today that size has increased to 19kb.

2019年07月20日04分20秒

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.

2019年07月20日04分20秒

Tumerj arguing that it is useful does nothing to address the concern of being lightweight. The two are not related.

2019年07月20日04分20秒

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.

2019年07月20日04分20秒

how to tell it to use local time or Zulu?

2019年07月20日04分20秒

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

2019年07月21日04分20秒

is there a way to do this. $.datepicker.formatDate('yy-mm-dd', new Date("txtAdvDate".Val()); or some thing like that

2019年07月21日04分20秒

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.

2019年07月21日04分20秒

Pomster - try using this: document.getElementById(id).value = $.datepicker.formatDate('yy-mm-dd', new Date());

2019年07月21日04分20秒

MDN is also a great reference: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

2019年07月20日04分20秒

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.

2019年07月20日04分20秒

It should be accepted answer, because it gives the required format (01-01-2000, not 1-1-2000)

2019年07月21日04分20秒

new Date().toISOString().slice(0,10) // "2015-04-27"

2019年07月20日04分20秒

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.

2019年07月20日04分20秒

abimelex done. Hope it is clearer now.

2019年07月20日04分20秒

thanks for adding the links to the source (: - see also developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… and developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

2019年07月20日04分20秒

I couldn't find a way to feed datejs with milliseconds to create a date. Like so: var dateTime = new Date(); dateTime.setTime(milliseconds);

2019年07月20日04分20秒

25k? Just for dates? Ouch.

2019年07月20日04分20秒

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.

2019年07月20日04分20秒

TylerForsythe I added a hint / warning about that.

2019年07月20日04分20秒

lol the date script is out of date...

2019年07月20日04分20秒

Enhanced it a bit for my purposes to support AM/PM - see below

2019年07月20日04分20秒

WHK But I still like momentjs more :D

2019年07月20日04分20秒

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?

2019年07月20日04分20秒

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

2019年07月20日04分20秒

WHK For console.log(new Date('2014-06-01')) -> May I think it has something to do with the timezone :D

2019年07月20日04分20秒

Attempting to actually answer the question won't get you many votes. Just nominate a popular library and see your score fly!!

2019年07月20日04分20秒

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

2019年07月20日04分20秒

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.

2019年07月20日04分20秒

is this cross browser? and cross locale?

2019年07月21日04分20秒

Yes.Shows time in your (browser user) local time zone.

2019年07月20日04分20秒

Source code references in linked article are dead, but fortunately someone put it on Github: github.com/rvanbaalen/date-steroids

2019年07月21日04分20秒

replace operations are not really efficient, so it's a better practise to prevent it.

2019年07月20日04分20秒

what if I write, what is going to happen?console.log("The date is: " + dateFormat(new Date(), "DD/MM/YY"));

2019年07月21日04分20秒

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.

2019年07月21日04分20秒

mrzmyr Do you really think that formatting dates will be a performance bottleneck? Come on.

2019年07月20日04分20秒

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

2019年07月20日04分20秒

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

2019年07月21日04分20秒

Very good solution! var a = new Date(); a.format('yyyy-MM-d'); //Return 2013-08-16.

2019年07月21日04分20秒

this.getMonth(); fails in iOS

2019年07月21日04分20秒

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"

2019年07月21日04分20秒

I guess the new URL is depressedpress.com/javascript-extensions/dp_dateextensions

2019年07月21日04分20秒

you need the script linked "JavaScript Date Format" linked above

2019年07月20日04分20秒