我正在尝试验证一周中的某一天是否等于星期三 (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');
}
最佳答案
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');
}
关于Javascript如何在使用时区时通过getDay验证日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57187691/