gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:35:11 25 4
gpt4 key购买 nike

我正在尝试验证一周中的某一天是否等于星期三 (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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com