JavaScript's getDate returns wrong date
Asked Answered
P

12

57

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?

Petitionary answered 21/3, 2010 at 19:3 Comment(5)
just to be sure i have tested it here on the fly tlarson.com/script and it say 21 !!!Quicksand
is that the only javascript code on the page? you could be executed some other piece of code. Very strange indeed.Hollis
What is the language/country of your OS?Gasp
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.Fable
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.Evangelineevangelism
F
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
}
Fit answered 21/3, 2010 at 19:11 Comment(5)
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.Fipple
@ferr—ie8 (and perhaps others) do not recognise ISO 8601 formats and will return an invalid date.Solatium
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?Mediocrity
@Arendax, the months on Javascript Date objects are zero-based, meaning 0=Jan, 1=Feb, 2=Mar, etc...Martymartyn
@CMS Thanks but stupid that I didn't think of this :)Mediocrity
E
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.

Evangelineevangelism answered 6/2, 2013 at 22:45 Comment(1)
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);Repulsion
S
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().

Sinuosity answered 21/3, 2010 at 19:23 Comment(0)
K
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").
Klinger answered 27/6, 2018 at 11:53 Comment(2)
Please format your answer properly following the guideStonyhearted
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 ?Bencher
H
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.

Hendel answered 23/11, 2010 at 20:7 Comment(2)
@Jack This is not a question.Keldon
@Keldon it definitely isn't an answer either.Archducal
G
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?

Gasp answered 21/3, 2010 at 19:9 Comment(9)
i also have tested it on jsbin and it work nice! it return 21! ;-)Newby
I take issue with the statement 'There is no such thing as a JavaScript bug' bugzilla.mozilla.org/buglist.cgi?quicksearch=javascriptAleedis
@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.Cotsen
The same problem in Firefox 18.0.1. The mess is day 21. All other days works fine!Evangelineevangelism
upvoted because I had no idea you could test JavaScript in the address barStereochromy
@AndyEarnshaw by that logic, there are no bugs in MS Word, Excel or Linux because there are different implementations of each one.Neil
@cbmeeks: I don't think you understood what I wrote, as what you said isn't analogous at all. I'm not sure if that's a bug in my writing or your comprehension!Cotsen
@AndyEarnshaw could be either one I guess...or maybe a little of both. But, take what you said...word for word....and replace "JavaScript" with "Microsoft Word". Does what you say still sound reasonable? Maybe it does. Maybe it doesn't. Either way, I've already lost interest. lolNeil
Downvoted because you made a pretty bold statement that was simply wrong. The real problem is that Date is subject to time zone variations, which are localized. So you're in a location that isn't using pushing the clock an hour forward/backwards. And so you see the expected behavior. But that doesn't mean others are not seeing the expected behavior.Fraktur
N
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.

Nicolanicolai answered 21/3, 2010 at 19:9 Comment(1)
@Anubis: I can't see the picture you linked.Nicolanicolai
A
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');
Aquarist answered 3/8, 2017 at 19:49 Comment(1)
Add code examples for more clarity regarding the question.Defrost
A
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.

Airdrie answered 21/3, 2010 at 19:42 Comment(0)
H
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"));
} 
Heist answered 21/3, 2010 at 21:50 Comment(0)
L
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);
Lecturer answered 28/2, 2014 at 0:1 Comment(0)
M
-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

Marriageable answered 21/3, 2010 at 21:2 Comment(2)
You can create Date objects by passing string arguments which look like dates: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…Formless
should be date.setMonth(date_elements[1]-1)Ardine

© 2022 - 2024 — McMap. All rights reserved.