javascriptdatetime

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


Solution

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