56

The following script returns 20 instead of 21!

var d = new Date("2010/03/21");
document.write(d.getDate());

What am I doing wrong? Is this a JavaScript bug?

5
  • just to be sure i have tested it here on the fly tlarson.com/script and it say 21 !!! Mar 21, 2010 at 19:09
  • is that the only javascript code on the page? you could be executed some other piece of code. Very strange indeed. Mar 21, 2010 at 19:17
  • What is the language/country of your OS?
    – Jader Dias
    Mar 21, 2010 at 19:41
  • Not sure how you got this bug but I got it while running javascript unit tests through the headless PhantomJS browser. I'm glad I found this question. I won't be able to use parse the way I was but at least I know now I wasn't crazy.
    – Brett
    Oct 18, 2011 at 20:46
  • I've found exactly the same situation. The only day with problem is day 21. All other dates works fine. My browser is Firefox 18.0.1. Feb 6, 2013 at 21:31

12 Answers 12

64

The Date.parse method is implementation dependent (new Date(string) is equivalent to Date.parse(string)).

While this format will be available on modern browsers, you cannot be 100% sure that the browser will interpret exactly your desired format.

I would recommend you to manipulate your string, and use the Date constructor with the year, month and day arguments:

// parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
5
  • 9
    I have found that using new Date("2010-03-21T00:00:00") returns the correct date. Note the T00:00:00 to add the timestamp.
    – ferr
    Apr 11, 2016 at 18:07
  • 1
    @ferr—ie8 (and perhaps others) do not recognise ISO 8601 formats and will return an invalid date.
    – RobG
    May 19, 2016 at 22:48
  • Little bit late, but why do you retract one month from the month property? It is necessary for a working date, otherwise it is one month too early, but why?
    – Max
    Jan 25, 2018 at 20:05
  • 2
    @Arendax, the months on Javascript Date objects are zero-based, meaning 0=Jan, 1=Feb, 2=Mar, etc... Jan 25, 2018 at 21:56
  • @CMS Thanks but stupid that I didn't think of this :)
    – Max
    Jan 27, 2018 at 12:52
40

It's a daylight saving time issue, because Date() uses local time.

I live in Brazil and Oct-21-2012 is the start of daylight saving time in most of my country, so local dates at Oct-21-2012 between 0:0 and 1:0 doesn't exist in Brazil!

Some people comment here that it works. It happens because the right or wrong hour return depends on the local user country.

See: http://www.timeanddate.com/news/time/brazil-dst-2012.html

In Brazil, in 2012 Java thinks that DST starts at Oct-14 (actually it start at 1 week later)

var dt = new Date(2012,9,14); 
alert(dt.getHours());

produces 1 and

See: http://www.timeanddate.com/time/dst/2013.html

The solution is use UTC (Coordinated Universal Time) time, because there is no Daylight Saving changes and you use a kind of abstract time. In most practical applications there is no problem.

var dt = new Date( Date.UTC(2012, 9, 21, 8, 5, 12));
alert( (dt.getUTCMonth()+1) + '/' + dt.getUTCDate() + '/' + 
        dt.getUTCFullYear() + " " + dt.getUTCHours()+ ':' + 
        dt.getUTCMinutes() + ':' + dt.getUTCSeconds() );

it's easier if someone doesn't use hours, minutes and seconds, just place a dummy hour value greater or equal than 1, as I have shown above.

1
  • 3
    I agree that the issue has to do with DST but you made mistakes in your examples. Remember that in javascript Date constructor months start at 0, so if you want to refer to Oct-21-2012, you have to create: new date(2012,9,21);
    – lboullo0
    Jul 7, 2014 at 13:37
17

Any chance it's treating the string argument as UTC and the resulting Date object as local time, or vice versa? That could throw it off. Compare d.getDate() to d.getUTCDate().

0
10

It is the time zone which plays a major part here. The Date() function will add your time zone to the date which you are giving as an input. For example: I gave the input like this:

alert(new Date("2018-09-15"));

The result for me is :

Sat Sep 15 2018 05:30:00 GMT+0530 (India Standard Time)

The timezone +05:30 is added to my input's time( you can see in the above result..05:30:00 is being added to the date. Now what I'm telling is if you are in the time zone less than 0 [countries like brazil, mexico,chile,etc... having timezone less than 0] then it will add to your date input (eg: time zone is UTC−05:00. It will subtract -5:00 from the date given.

VahidN, you got the result 20 because you are in the time zone less than 0 (-1è : 00`, etc...)

The solution is reset your time zone to 0. Like this:

Date("2010-03-21T00:00:00").
2
  • Please format your answer properly following the guide
    – Hearen
    Jun 27, 2018 at 12:00
  • And why does an ISO time string throw an error? i.e. 2010-03-21T00:00:00.000Z or 2010-03-21T00:00:00.135Z ?
    – Andru
    Feb 8, 2021 at 13:05
4

I also get a deviation of one day through getDate(), but I note that getUTCDate() returns the expected value. The problem was seen in FF 3.6.12, but the same code running on Chrome was fine.

My debug code:

var date="2010-11-04";
alert(date);
var d = new Date(date)
alert(d.toDateString()+": "+ d.getDate()+" UTC "+d.getUTCDate());

This gave an output (FireFox):

Wed Nov 03 2010: 3 UTC 4

Chrome is fine. So something is up somewhere - perhaps a bug, but more likely a timezone/UTC parameter issue. Reminds me of where PHP date() will return 23 hours in a day if the timezone changed that day etc. Buggered if I know what it is, though.

2
  • @Jack This is not a question.
    – Ivan
    Jun 27, 2018 at 12:44
  • @Ivan it definitely isn't an answer either.
    – Jack
    Jun 27, 2018 at 18:37
2

I wrote the following code in my browser's address bar and the result was 21

javascript:alert(new Date("2010/03/21").getDate())

There is no such thing as a Javascript bug, since there is many Javascript implementations, so you'll want to refer to a specific implementation.

The implementation I tested was Chrome 4.1.249. What's yours?

9
  • i also have tested it on jsbin and it work nice! it return 21! ;-) Mar 21, 2010 at 19:17
  • 1
    I take issue with the statement 'There is no such thing as a JavaScript bug' bugzilla.mozilla.org/buglist.cgi?quicksearch=javascript
    – John K
    Mar 21, 2010 at 19:52
  • 1
    @jdk: I think he was referring to the fact there's many implementations of "JavaScript", so what may be a bug in one implementation isn't a bug in "JavaScript" itself, just a bug in the implementation. So really, it's not an incorrect statement to make.
    – Andy E
    Mar 21, 2010 at 19:59
  • The same problem in Firefox 18.0.1. The mess is day 21. All other days works fine! Feb 6, 2013 at 21:33
  • upvoted because I had no idea you could test JavaScript in the address bar Sep 9, 2016 at 13:16
1

I tested this code in Firefox 3.6 and IE 8:

<script type="text/javascript">

var d = new Date("2010/03/21");
document.write(d.getDate());

</script> 

It's showing the right date: 21

For more information, look at: JavaScript Date Object

You can also read about JavaScript Compatibility considerations at Wikipedia.

1
  • 1
    @Anubis: I can't see the picture you linked. Mar 21, 2010 at 19:19
1

When giving new Date a string date, the string need to include the timezone, otherwise it will be interpreted differently from browser to other (due to different javascript implementations) and from machine to other (due the difference of the local time zone)

new Date('2017-07-31T10:00:00-0500');

instead of

new Date('2017-07-31T10:00:00');

1
  • 2
    Add code examples for more clarity regarding the question. Aug 3, 2017 at 19:53
0

http://jsbin.com/aqoki3/edit - here with code you posted I get 21. So its not JS bug. Maybe its bug in your browser implementation (of JS).
So to correctly init your date var use new Date(year, month, date [, hour, minute, second, millisecond ]) (https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Date). This way you will be sure that day is 21 becouse you implicitly set it to 21.

0

I get the same date (21) in firfox,safari,chrome,opera and IE, whether I use the string "2010/03/21" or the integer date arguments (2010,2,21).

I am using a windows machine and new versions of the browsers-

you can test to see if your client parses a different date from the string, which is the only place I see for a problem.

if(new Date("2010/03/21")- new Date(2010,2,21)){
alert(new Date("2010/03/21"));
} 
0

Make sure the number month you are using is -1, If you are looking at June, you need to do (6-1) for the month, when create

   var date_obj = new Date(y,(m-1),d);
-3

You cant't create Date object by passing string argument shows like date.

Create Like this way.

var str_date = "2010/03/21";
var date = new Date();
var date_elements = str_date.split("/");

date.setYear(date_elements[0]);
date.setMonth(date_elements[1]);
date.setDay(date_elements[2]);

alert(date.toString);

give attention on date.toString method. it returns full date String. date.getDate will only give you day of that day.

for more info of Date object, refer www.w3school.com

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.