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

Joe*_*erg 3 javascript datetime

我试图验证一周中的某一天是否等于星期三 (3),如果我按以下方式操作,这很有效。

var today = new Date();

if (today.getDay() == 3) {
  alert('Today is Wednesday');
} else {
	alert('Today is not Wednesday');
}
Run Code Online (Sandbox Code Playgroud)

但我无法对时区做同样的事情。

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');
}
Run Code Online (Sandbox Code Playgroud)

MH2*_*2K9 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');
}
Run Code Online (Sandbox Code Playgroud)


Adi*_*chi 8

正如函数“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');
}
Run Code Online (Sandbox Code Playgroud)

  • `getDay()` 根据文档“根据当地时间返回指定日期的星期几”。所以这个答案是不正确的。输入字符串无关紧要。返回值基于系统时区。 (4认同)