This question already has an answer here:
- Converting a string to a date in JavaScript 30 answers
Having this string 30/11/2011
. I want to convert it to date object.
Do I need to use :
Date d = new Date(2011,11,30); /* months 1..12? */
or
Date d = new Date(2011,10,30); /* months 0..11? */
?
There are multiple methods of creating date as discussed above. I would not repeat same stuff. Here is small method to convert String to Date in Java Script if that is what you are looking for,
Always, for any issue regarding the JavaScript spec in practical, I will highly recommend the Mozilla Developer Network, and their JavaScript reference.
As it states in the topic of the Date object about the argument variant you use:
And about the months parameter:
Clearly, then, you should use the month number 10 for November.
P.S.: The reason why I recommend the MDN is the correctness, good explanation of things, examples, and browser compatibility chart.
The syntax is as follows:
so
is correct; day, hour, minute, second, millisecond are optional.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
I can't believe javascript isn't more consistent with parsing dates. And I hear the default when there is no timezone is gonna change from UTC to local -- hope the web is prepared ;)
I prefer to let Javascript do the heavy lifting when it comes to parsing dates. However it would be nice to handle the local timezone issue fairly transparently. With both of these things in mind, here is a function to do it with the current status quo -- and when Javascript changes it will still work but then can be removed (with a little time for people to catch up with older browsers/nodejs of course).
We need a date object regardless; so createone. If there is a timezone, we are done. Otherwise, create a local timezone string using the +hh:mm format (more accepted than +hhmm).
You definitely want to use the second expression since months in JS are enumerated from 0.
Also you may use Date.parse method, but it uses different date format:
Very simple:
Date should be in ISO format yyyy/MM/dd.