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');

}


POPMUISE
浏览 197回答 2
2回答

LEATH

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');}

PIPIONE

正如函数“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');}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript