JavaScript's getDate returns wrong date

JavascriptGetdate

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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
}

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

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?

Solution 7 - Javascript

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.

Solution 8 - Javascript

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)

for example:

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

instead of

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

Solution 9 - Javascript

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.

Solution 10 - Javascript

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"));
} 

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVahidNView Question on Stackoverflow
Solution 1 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JavascriptPaulo BuchsbaumView Answer on Stackoverflow
Solution 3 - JavascripteyelidlessnessView Answer on Stackoverflow
Solution 4 - JavascriptSteven BalaView Answer on Stackoverflow
Solution 5 - JavascriptChrisView Answer on Stackoverflow
Solution 6 - JavascriptJader DiasView Answer on Stackoverflow
Solution 7 - JavascriptLeniel MaccaferriView Answer on Stackoverflow
Solution 8 - JavascriptAnis DkhilView Answer on Stackoverflow
Solution 9 - JavascriptNilColorView Answer on Stackoverflow
Solution 10 - JavascriptkennebecView Answer on Stackoverflow
Solution 11 - JavascriptCG_DEVView Answer on Stackoverflow
Solution 12 - JavascriptParthView Answer on Stackoverflow