Date Object and UTC

Why does this return the 31st instead of the 1st? . As I understand it, the UTC method requires 3 parameters (full year, month, day), and the day parameter must be an integer from 1 to 31. Since getDate() returns with an integer from 0 to 31, I also suspect that 0 it will be an opportunity.

 firstDay = new Date(Date.UTC( 2011 , 7 , 1 )).getDate(); // returns 31 (last day of this month) 

Let me clarify and say that this is not a special case. If the day parameter is 2, 3 or 4, this will return 1, 2, 3, etc.

+2
source share
3 answers

Your time zone offset is negative since -4. So, 7/1/2011 at 12:00 AM minus 4 hours - 03/31/2011 20:00. Date.UTC accepts additional parameters that you can use to pass hours, minutes, seconds, and milliseconds.

But really, if you do not want the time zone adjustment to use new Date(year, month, day)

 firstDay = new Date(2011 , 7 , 1).getDate(); // returns 1 (first day of this month) 
+2
source

I am in (GMT-0700) Pacific Time . Here are the results when I do the following:

 new Date( 2011, 7, 1 ); // -> Mon Aug 01 2011 00:00:00 GMT-0700 (Pacific Daylight Time) new Date( Date.UTC( 2011, 7, 1 ) ); // -> Sun Jul 31 2011 17:00:00 GMT-0700 (Pacific Daylight Time) 

Please note that pulling UTC gives me the date / time at my current location 7 hours before the specified date, because I am 7 hours less than Greenwich Mean Time.

+1
source

This is what you are looking for:

 new Date(Date.UTC(2011, 7, 1) + ((new Date).getTimezoneOffset() / 60) * 3600000).getDate(); 

Explanation:

(new Date).getTimeZoneOffset(); // will retrieve the timezone offset, (420 in my case PST)

offset / 60; // we divide by 60 so we can get the number of hours between UTC and me

(offset / 60) * 360000 // is 60 (seconds) * 60 (minutes) * 1000 (ms)

+ Date.UTC(2011, 7, 1) // will give us the correct Date always

0
source

All Articles