223

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? */

?

2
  • 1
    Neither. See the @IgorDymov answer. Your query is about a "String", rather than the order the three numbers should be in. Commented Oct 23, 2014 at 19:42
  • This question is somewhat confusing--the first sentence and the title are about string parsing, whereas the rest of the question is about constructing a Date from a set of integers. I'm voting to close as a duplicate because I'm assuming that the title is correct and you're looking for string-parsing. Commented Apr 10, 2017 at 20:27

8 Answers 8

302
var d = new Date(2011,10,30);

as months are indexed from 0 in js.

Sign up to request clarification or add additional context in comments.

5 Comments

I think it should be var d = new Date(2011,10,30);
Surprised someone noticed this about 1.5 years and 24,000+ views later.
or we can use new Date(2011,11,0)
it can also pick the date directly, as a single string const date = new Date("2018-05-09")
Be cautious! const date = new Date("2018-05-09") won't give you a correct date if your timezone is negative. Use const date = new Date("2018-05-09T00:00:00") or const date = new Date("2018/05/09") or const date = new Date(2018, 4, 9) instead.
109

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:

var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);

5 Comments

Beware of timezone issues when using the parse method.
Beware of Javascript silently returning a completely different date than the one parsed, if the parsed date happens not to be valid (such as February 30).
Also beware that Date.parse() returns a number, specifically the ms since 1970. Whereas Dogbert's answer will return a JS Date object, with a robust selection of methods available from __proto__. Demo in jsFiddle
This returns a number, not a date.
According to official documentation: Note: Parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Avoid creating Date objects by parsing strings. Instead, build your own function that understands the year, month and day from the string you have, and then create the Date by passing the distinct numbers to the constructor
70

The syntax is as follows:

new Date(year, month [, day, hour, minute, second, millisecond ])

so

Date d = new Date(2011,10,30);

is correct; day, hour, minute, second, millisecond are optional.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

1 Comment

Actually, day is also optional according to the link. It defaults to the first day of the month.
65

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,

function compareDate(str1){
// str1 format should be dd/mm/yyyy. Separator can be anything e.g. / or -. It wont effect
var dt1   = parseInt(str1.substring(0,2));
var mon1  = parseInt(str1.substring(3,5));
var yr1   = parseInt(str1.substring(6,10));
var date1 = new Date(yr1, mon1-1, dt1);
return date1;
}

4 Comments

This was really useful and should be the top answer since it actually answers the question in an adaptable way depending on your date string format (and without any risk of timezone issues).
For me this also was the best answer.
When I stumbled across my requirement to do this and learnt that months indexed from 0, I pondered on a couple of ways on how to alter my month value. I scrolled down some more and found this :-) thanks!
This actually answers the question properly. "Date Object from String". Thanks for this answer.
40

Very simple:

var dt=new Date("2011/11/30");

Date should be in ISO format yyyy/MM/dd.

4 Comments

As I know, the official ISO8601 format is yyyy-MM-dd (en.wikipedia.org/wiki/ISO_8601)
Yes it worked by doing new Date("2019-12-21 07:25:00")
@ValterEkholm it's working fine in chrome and ff, but not in safari
I think using backslashes might yield more predictable results ... see stackoverflow.com/questions/70481329/…
15

First extract the string like this

var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);

Then,

var d = new Date( dateString[3], dateString[2]-1, dateString[1] );

1 Comment

No, let the engine handle it for you and use the suggested Date.parse
10

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:

new Date(year, month, day [, hour, minute, second, millisecond ])

And about the months parameter:

month Integer value representing the month, beginning with 0 for January to 11 for December.

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.

Comments

3

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

function strToDate(dateStr)
{
    var dateTry = new Date(dateStr);

    if (!dateTry.getTime())
    {
        throw new Exception("Bad Date! dateStr: " + dateStr);
    }

    var tz = dateStr.trim().match(/(Z)|([+-](\d{2})\:?(\d{2}))$/);

    if (!tz)
    {
        var newTzOffset = dateTry.getTimezoneOffset() / 60;
        var newSignStr = (newTzOffset >= 0) ? '-' : '+';
        var newTz = newSignStr + ('0' + Math.abs(newTzOffset)).slice(-2) + ':00';

        dateStr = dateStr.trim() + newTz;
        dateTry = new Date(dateStr);

        if (!dateTry.getTime())
        {
            throw new Exception("Bad Date! dateStr: " + dateStr);
        }
    }

    return dateTry;
}

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.