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