admin管理员组文章数量:1221308
I am trying to verify that the day of the week is equal to Wednesday (3), and this works well if I do as following.
var today = new Date();
if (today.getDay() == 3) {
alert('Today is Wednesday');
} else {
alert('Today is not Wednesday');
}
I am trying to verify that the day of the week is equal to Wednesday (3), and this works well if I do as following.
var today = new Date();
if (today.getDay() == 3) {
alert('Today is Wednesday');
} else {
alert('Today is not Wednesday');
}
But I am unable to do the same with a time zone.
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');
}
Share
Improve this question
asked Jul 24, 2019 at 16:41
Joe BergJoe Berg
3816 silver badges19 bronze badges
3 Answers
Reset to default 12new Date().toLocaleString() returns a string representing the given date according to language-specific conventions. So can do this
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');
}
As the function 'toLocaleString' implies, it returns a String. The 'getDay' exists on a Date type.
So, to use the 'getDay', You'll need to cast the String back to Date.
try:
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');
}
The code below returns the day of timezone. It could be used for the required checks.
Date.prototype.getDayTz = function (timezone)
{
timezone = Number(timezone);
if (isNaN(timezone)) {
return this.getUTCDay();
}
const UTCHours = this.getUTCHours();
let daysOffset = 0;
if (
UTCHours + timezone < 0 ||
UTCHours + timezone > 24)
) {
daysOffset = Math.sign(timezone);
}
return (7 + (this.getUTCDay() + daysOffset)) % 7;
};
var today = new Date();
if (today.getDayTz(-5) == 3) {
alert('Today is Wednesday in New York');
} else {
alert('Today is not Wednesday in New York');
}
本文标签: datetimeJavascript how to verify day by getDay when using timezoneStack Overflow
版权声明:本文标题:datetime - Javascript how to verify day by getDay when using timezone - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739323624a2158147.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论