日期对象和UTC方法

Date Object and UTC Method

本文关键字:方法 UTC 对象 日期      更新时间:2023-09-26

为什么返回第31个而不是第1个?我理解的UTC方法需要3个参数(整年、月、日),其中day参数必须是1 ~ 31之间的整数。因为getDate()返回的是0到31之间的整数,所以我也怀疑0也是可能的。

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

让我澄清一下,这不是一个特例。如果day参数为2、3或4,这将返回1、2、3,等等。

您的时区偏移量为负值,例如-4。所以7/1/2011中午12点减去4小时等于6/31/2011晚上8点。日期。UTC有额外的参数,可以用来传递小时、分钟、秒和毫秒。

但实际上,如果您不想要时区调整,请使用new Date(year, month, day)

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

我在(GMT-0700) Pacific Time。以下是我执行以下操作时的结果:

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)

请注意,提取UTC时间会给我当前位置的日期/时间,比指定的日期早7小时,因为我比格林威治标准时间晚7小时。

这就是你要找的:

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

解释:

(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