213

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

?

John Hascall
  • 9,176
  • 6
  • 48
  • 72
Bader
  • 3,656
  • 9
  • 38
  • 55
  • 1
    Neither. See the @IgorDymov answer. Your query is about a "String", rather than the order the three numbers should be in. – Jesse Chisholm Oct 23 '14 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. – Kyle Strand Apr 10 '17 at 20:27

8 Answers8

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

as months are indexed from 0 in js.

Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • 33
    I think it should be var d = new Date(2011,10,30); – Yoosaf Abdulla Oct 01 '13 at 17:07
  • 74
    Surprised someone noticed this about 1.5 years and 24,000+ views later. – Dogbert Oct 02 '13 at 06:18
  • 1
    or we can use `new Date(2011,11,0) ` – Mahi Mar 23 '17 at 10:29
  • 16
    it can also pick the date directly, as a single string `const date = new Date("2018-05-09")` – Matt May 10 '18 at 21:54
  • 2
    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. – Edmund Wang Aug 30 '22 at 07:56
101

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);
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
Igor Dymov
  • 16,230
  • 5
  • 50
  • 56
  • 3
    Beware of timezone issues when using the parse method. – Alex May 20 '14 at 16:41
  • 3
    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). – jforberg Aug 21 '14 at 13:52
  • 6
    Also beware that [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](https://jsfiddle.net/KyleMit/bt8gwtyb/) – KyleMit Apr 11 '17 at 19:19
  • 4
    This returns a number, not a date. – Alisson Reinaldo Silva Jul 04 '17 at 14:39
  • 2
    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 – Alex Christodoulou Apr 30 '20 at 12:01
68

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

Serhat Ates
  • 885
  • 1
  • 12
  • 18
Christopher Tokar
  • 11,644
  • 9
  • 38
  • 56
63

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;
}
Liam
  • 27,717
  • 28
  • 128
  • 190
Mayank
  • 796
  • 1
  • 10
  • 12
  • 4
    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). – Kosta Kontos Dec 02 '15 at 08:31
  • For me this also was the best answer. – Stephan Kristyn Feb 02 '16 at 17:29
  • 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! – codaamok Mar 28 '16 at 13:34
  • This actually answers the question properly. "Date Object from **String**". Thanks for this answer. – Sukanta Paul Apr 23 '18 at 18:41
40

Very simple:

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

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

Pearl
  • 8,373
  • 8
  • 40
  • 59
14

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] );
vadru
  • 73
  • 4
pashaplus
  • 3,596
  • 2
  • 26
  • 25
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.

Sune Rasmussen
  • 956
  • 4
  • 14
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).

Gerard ONeill
  • 3,914
  • 39
  • 25