Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript how to verify day by getDay when using timezone

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');
}
like image 886
Joe Berg Avatar asked Jun 08 '26 08:06

Joe Berg


1 Answers

new 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');
}
like image 105
MH2K9 Avatar answered Jun 10 '26 22:06

MH2K9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!