I am trying to convert "July 24 2013" to "DD-MM-YYYY" with javascript but I keep getting and error.
I am using new Date('July 24 2013').format("DD-MM-YYYY");
What am I missing?
I am trying to convert "July 24 2013" to "DD-MM-YYYY" with javascript but I keep getting and error.
I am using new Date('July 24 2013').format("DD-MM-YYYY");
What am I missing?
Date
object doesn't have.format()
method. If you work with date and time actively I'd recommend you to use MomentJS library then. It has a lot of useful functionality to work with time and date.For example:
moment('July 24 2013', 'MMMM D YYYY').format('MMMM D YYYY, h:mm:ss a');
To simplify a little bit...the problem is because the format used by browser to store dates is not always the same (and the one you're passing to Date constructor is not allowed). It's allowed by the standard, what is required is the browser can parse the format produced by itself (see §15.9.4.2).
Usually to work directly with date format is not a good idea, not only because browser specific implementation but because of globalization (this is especially true for a web application with a virtual world wide audience).
The only format you're sure every browser will read is
YYYY-MM-DDTHH:mm:ss.sssZ
(see §15.9.1.15) so in your case you should change your custom parsing/formatting to that.Take a look to this and this posts on SO for other details (or this little tutorial about dates).
What I suggest, if you work with dates across browsers and locales, is to use a good library to abstract all this details. I found this one is pretty strong and easy to use (it replaces standard
Date
functions so you may not even need to change one single line of code).I would highly advise using momentjs!
Simple as that!
There is no Data.prototype.format function in JavaScript.
You're best off looking at open source options for localizing dates. I've had success with
There's also:
Bellow is simple, portable, pure JS implementation based on Java date format:
Above code is based on http://llamalab.com/js/date/Date.js (LGPL)