最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

datetime - Javascript how to verify day by getDay when using timezone - Stack Overflow

programmeradmin1浏览0评论

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
Add a comment  | 

3 Answers 3

Reset to default 12

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

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');
}
发布评论

评论列表(0)

  1. 暂无评论