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)
正如函数“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)
| 归档时间: |
|
| 查看次数: |
1799 次 |
| 最近记录: |