Javascript 如何在使用时区时通过 getDay 验证日期

问题描述 投票:0回答:3

我正在尝试验证一周中的哪一天等于星期三 (3),如果我按照以下步骤操作,效果会很好。

var today = new Date();

if (today.getDay() == 3) {
  alert('Today is Wednesday');
} else {
	alert('Today is not Wednesday');
}

但我无法对时区执行同样的操作。

var todayNY = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});

if (todayNY.getDay() == 3) {
  alert('Today is Wednesday in New York');
} else {
	alert('Today is not Wednesday in New York');
}

javascript datetime
3个回答
11
投票

new Date().toLocaleString() 根据特定于语言的约定返回表示给定日期的字符串。所以可以这样做

var todayNY = new Date();

var dayName = todayNY.toLocaleString("en-US", {
    timeZone: "America/New_York",
    weekday: 'long'
})

if (dayName == 'Wednesday') { // or some other day
    alert('Today is Wednesday in New York');
} else {
    alert('Today is not Wednesday in New York');
}


6
投票

正如函数“toLocaleString”所暗示的那样,它返回一个字符串。 “getDay”存在于日期类型中。

因此,要使用“getDay”,您需要将字符串转换回日期。

尝试:

var todayNY = new Date().toLocaleString("en-US", {
  timeZone: "America/New_York"
});
todayNY = new Date(todayNY);
if (todayNY.getDay() == 3) {
  alert('Today is Wednesday in New York');
} else {
  alert('Today is not Wednesday in New York');
}


0
投票

下面的代码返回时区的日期。它可用于所需的检查。

Date.prototype.getDayTz = function (timezone)
{
  timezone = Number(timezone);

  if (isNaN(timezone)) {
    return this.getUTCDay();
  }
  
  const UTCHours = this.getUTCHours();
  let daysOffset = 0;

  if (
    UTCHours - timezone < 0 ||
    UTCHours + timezone > 24) 
  ) {
    daysOffset = Math.sign(timezone);
  }
  
  return (7 + (this.getUTCDay() + daysOffset)) % 7;
};

var today = new Date();

if (today.getDayTz(-5) == 3) {
  alert('Today is Wednesday in New York');
} else {
  alert('Today is not Wednesday in New York');
}
© www.soinside.com 2019 - 2024. All rights reserved.