首页 > 解决方案 > Javascript如何在使用时区时逐日验证getDay

问题描述

我正在尝试验证一周中的哪一天等于星期三 (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');
}

标签: javascriptdatetime

解决方案


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

因此,要使用“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');
}


推荐阅读