Javascript setUTCMonth does not work for November [duplicate] - javascript

This question already has answers here:
Javascript date parsing bug - fails for dates in June (??)
(5 answers)
Closed 8 years ago.
I'm getting some really strange behaviour with Javascript date objects.
var t = new Date();
t.setUTCFullYear(2014);
t.setUTCMonth(10);
t.setUTCDate(20);
console.log(t);
This returns:
Date {Sat Dec 20 2014 10:26:23 GMT-0800 (PST)}
Whereas if you use t.setMonth(10), you correctly get November. Am I doing something wrong?

This will work as expected tomorrow.
Today (October 31st), t is initialized with its day as 31. When you set the month to November, you're setting "November 31st", which is corrected to December 1st.
Then you set the date to 20, but the month has already changed. Set the date first, or better yet, use the two-argument verson of setUTCMonth():
t.setUTCMonth(10, 20);

Maybe I'm missing something (EDIT: I was, Paul's answer covers it), but you're right. However, this works:
var t = new Date();
t.setUTCFullYear(2014);
t.setUTCMonth(10, 20); // Set day here instead
console.log(t); // Thu Nov 20 2014 12:40:42 GMT-0600 (Central Standard Time)
It also works if you switch the order of the set statements:
var t = new Date();
t.setUTCFullYear(2014);
t.setUTCDate(20);
t.setUTCMonth(10);

The problem is a mixture of particular dates and the order of setting individual parts of the date. If you step through what's happening it becomes clearer:
New date is initialised as today: Oct 31, 2014
Setting the year to 2014: no effect
Setting the month to November: Nov 31, 2014 is interpreted as Dec 1, 2014
Setting the date to 20: Dec 20, 2014

Related

JavaScript newDate(Date.UTC) Results in the Wrong Month [duplicate]

using Mozilla Firefox Firebug:
var myDate = new Date(2012, 9, 23, 0,0,0,0);
myDate;
Date {Tue Oct 23 2012 00:00:00 GMT-0400 (Eastern Daylight Time)}
Why does javascript create the date with the wrong month?
No, javascript's Date months start with 0, so 9 is a 10th month and it is October
Reference:
new Date(year, month [, day, hour, minute, second, millisecond]);
[...]
month
Integer value representing the month, beginning with 0 for January to 11 for December.
In the javascript world months begin with zero!
kind of weird to me.
Anyhow, 9 is NOT September, but rather 9 is October.
Use a string as a parameter to avoid that weird behavior of Date constructor.
Example:
const myDate = new Date('2021-08-13'); // Result: Fri Aug 13 2021 02:00:00 GMT+0200...
In javascript Date object mounts are starting from ( 0 to 11 ) its funny :)
just always write
new Date(yea,month - 1,seconds ,millisecond)

How to get day relative to current timezone using Date in Javascript? [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
new Date('2019-01-01')
Mon Dec 31 2018 19:00:00 GMT-0500 (Eastern Standard Time)
new Date('2019-01-01').getDate()
31
I would be expecting 1 to be the result. How can I get day relative to current timezone using Date in Javascript?
The constructor appears to set the Date object's value using the UTC time that corresponds to the string argument (midnight on 2019-01-01) -- for which the local equivalent is Mon Dec 31 2018 19:00:00 GMT-0500 (Eastern Standard Time).
Storing local midnight would mean actually storing 5AM UTC, like:
new Date('2019-01-01T05:00:00');
Since we don't necessarily know the difference between local and UTC times in advance, we can find and use it dynamically like this:
let date = new Date("2019-01-01");
let offset = date.getTimezoneOffset(); // Returns the offset in minutes
date = new Date(date.getTime() + (offset * 60 * 1000)); // Adds the offset in milliseconds
console.log(date.toLocaleString());
For further reference,
- Here's a somewhat-related question (where the top answer actually recommends importing a library to handle these issues): How to add 30 minutes to a JavaScript Date object?,
- And here's good-ol' MDN's page on JS dates:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
If you populate the Date constructor with the timezone offset, you can instead use getUTCDate.
var date1 = new Date('August 19, 1975 23:15:30 GMT+11:00');
var date2 = new Date('August 19, 1975 23:15:30 GMT-11:00');
console.log(date1.getUTCDate());
// expected output: 19
console.log(date2.getUTCDate());
// expected output: 20

Why does Javascript convert times differently? [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 5 years ago.
These are my two codes:
var date1 = new Date('2017-04-23');
var date2 = new Date('April 23, 2017');
console.log(date1);
console.log(date2);
this is the results:
Sat Apr 22 2017 17:00:00 GMT-0700 (PDT)
Sun Apr 23 2017 00:00:00 GMT-0700 (PDT)
why is date1 showing as the 22nd at 17:00?
JavaScript's Date parsing behavior is somewhat unreliable. It seems that when you give it an ISO 8601 string such as `"2017-04-23" it interprets the date as being in your own timezone, but when you give it an arbitrary string, it will interpret it as a UTC date.
Since you are in the GMT-7 timezone, the 22nd at 17:00 is the 23rd at 00:00 in UTC, and when you print out a date object, it will always print out the UTC date and not the localized date.
So, in summary, both dates are getting set to the 23rd at 00:00, but in different timezones. The first is being set to Apr 23 00:00 UTC-7 and the second one is being set to Apr 23 00:00 UTC.
It might be a good idea to always explicitly set a timezone in order to avoid this ambiguity.

new Date() set to 31 december 2014 says 1st december instead

I am trying to convert a string to a Date object, and it works for all days except for December 31st where by object says December 1st instead of 31st. I have no idea why. Here is my JavaScript code:
var dt = new Date();
dt.setDate("31");
dt.setMonth("11");
dt.setFullYear("2014");
but my variable value is:
Mon Dec 01 2014 11:48:08 GMT+0100 (Paris, Madrid)
If I do the same for any other date, my object returns to the appropriate value. Do you have any idea what I did wrong?
The thing is, when you set a day first, you're still in the current month, so September. September has only 30 days so:
var dt = new Date(); /* today */
dt.setDate("31"); /* 1st Oct 2014 as should be by spec */
dt.setMonth("11"); /* 1st Dec 2014 */
dt.setFullYear("2014"); /* 1st Dec 2014 */
setMonth should before setDate: (not safe for Months less than 31 days)
var dt = new Date();
dt.setFullYear(2014);
dt.setMonth(11);
dt.setDate(31);
And setMonth's second parameter also could be used to set date.
var dt = new Date();
dt.setFullYear(2014);
dt.setMonth(11, 31);
If no arguments are provided for the constructor, it will use the current date and time according to system settings.
So, using setMonth and setDate separately would still cause unexpected result.
If the values set are greater than their logical range, the value will be auto adjusted to the adjacent value.
For example, if today is 2014-09-30, then
var dt = new Date();
dt.setFullYear(2014); /* Sep 30 2014 */
dt.setMonth(1); /* Mar 02 2014, see, here the auto adjustment occurs! */
dt.setDate(28); /* Mar 28 2014 */
To avoid this, set the values using the constructor directly.
var dt = new Date(2014, 11, 31);
It's because the first thing you do is
dt.setDate(31)
This sets the current date to 31. The current month is September which has 30 days, so it's wrapping it round.
If you were to print out the date after this point, it would say 1 October.
Assuming your intent is to set year, month and date simultaneously you could use the longer date constructor:
new Date(year, month, day, hour, minute, second, millisecond);
[...]
If at least two arguments are supplied, missing arguments are either
set to 1 (if day is missing) or 0 for all others.
So you would write:
var dt = new Date(2014, 11, 31);
As already established, setting one portion of date at a time can result in overflows:
var dt = new Date(2012, 1, 29); // Feb 29 2012
dt.setFullYear(2014); // Mar 01 2014 instead of Feb 28 2014
Moreover, setting month before date can still cause unexpected overflow (answers that recommend changing the order of methods are incorrect):
var dt = new Date(2014, 0, 31); // Jan 31 2014
dt.setFullYear(2014); // Jan 31 2014
dt.setMonth(1); // Mar 03 2014 instead of Feb 28 2014
dt.setDate(1); // Mar 01 2014
The why of the behaviour and how to avoid it has been amply explained.
But the real error in your code is that you shouldn't use the default constructor: new Date(). Your code will result in a Date on Dec. 13 with the current time. I doubt this is what you want. You should use the Date constructor that takes year, month and day as parameters.
The answers made clear that the right order for setting the date is:
setFullYear()
setMonth()
setDate()
I just want to point out that it´s also important to set the year at first, because of the 29. february in leapyears.
var dt = new Date();
dt.setFullYear(2014);
dt.setMonth(11);
dt.setDate(31);
Pass value as integer not string.. it will return u correct value..
Update -
above description is not correct.. the main issue was you need to put these three line in proper sequence.. Even After I corrected the sequence I forgot to correct the description.. :P

Convert One time to another time zone not work in IE [duplicate]

I have an issue -
The javascript Date("mm-dd-yyyy") constructor doesn't work for FF. It works fine for IE.
IE : new Date("04-02-2008") => "Wed Apr 2 00:00:00 EDT 2008"
FF2 : new Date("04-02-2008") => Invalid Date
So lets try another constructor. Trying this constructor Date("yyyy", "mm", "dd")
IE : new Date("2008", "04", "02"); => "Fri May 2 00:00:00 EDT 2008"
FF : new Date("2008", "04", "02"); => "Fri May 2 00:00:00 EDT 2008"
IE : new Date("2008", "03", "02"); => "Wed Apr 2 00:00:00 EDT 2008"
FF : new Date("2008", "03", "02"); => "Wed Apr 2 00:00:00 EDT 2008"
So the Date("yyyy", "mm", "dd") constructor uses an index of 0 to represent January.
Has anyone dealt with this?
There must be a better way than subtracting 1 from the months.
It is the definition of the Date object to use values 0-11 for the month field.
I believe that the constructor using a String is system-dependent (not to mention locale/timezone dependent) so you are probably better off using the constructor where you specify year/month/day as seperate parameters.
BTW, in Firefox,
new Date("04/02/2008");
works fine for me - it will interpret slashes, but not hyphens. I think this proves my point that using a String to construct a Date object is problemsome. Use explicit values for month/day/year instead:
new Date(2008, 3, 2);
nice trick indeed, which i just found out the hard way (by thinking thru it).
But i used a more natural date string with hyphen :-)
var myDateArray = "2008-03-02".split("-");
var theDate = new Date(myDateArray[0],myDateArray[1]-1,myDateArray[2]);
alert(theDate);
Using
var theDate = new Date(myDate[0],myDate[1]-1,myDate[2]);
Is fine, but it shows some strange behaviors when month and day values are erroneous.
Try casting a date where both myDate[1]-1 and myDate[2] have values of 55. Javascript still returns a date, though the input is obviously not correct.
I would have preferred javascript to return an error in such a case.
#Frank: you are right. When you need to validate date,
var theDate = new Date(myDate[0],myDate[1]-1,myDate[2]);
will not work.
What happens is that it keeps on adding the extra parameter. For example:
new Date("2012", "11", "57") // Date {Sat Jan 26 2013 00:00:00 GMT+0530 (IST)}
Date object takes the extra days (57-31=26) and adds it to the date we created.
Or if we try constructing a date object with:
new Date("2012", "11", "57", "57") //Date {Mon Jan 28 2013 09:00:00 GMT+0530 (IST)}
an extra 2 days and 9 hours (57=24+24+9) are added.
You're quite right, month is indicated as an index, so January is month number 0 and December is month number 11 ...
-- and there is no work-around as it is stated clearly in the ECMA-script-definition, though simple tricks commonly will work:
var myDate = "2008,03,02".split(",");
var theDate = new Date(myDate[0],myDate[1]-1,myDate[2]);
alert(theDate);
Bold statement.
This might have your interest: JavaScript Pretty Date.

Categories

Resources