0

每次时钟为 15:00 及以上时,我需要将莫斯科时间的当前日期增加 1 天。我是在当地时间做的,但是按照莫斯科时间(UTC + 3)我做不到

  function date() {
  const today = new Date();
  const t = today.getHours();
  const dtfRU = new Intl.DateTimeFormat('ru', {
    month: 'long', day: '2-digit',
  });

  if (t >= 15) {
    today.setDate(today.getDate() + 1);
    document.querySelector('.date').innerHTML = dtfRU.format(today);
  } else document.querySelector('.date').innerHTML = dtfRU.format(today);

}

document.addEventListener("DOMContentLoaded", date);

4

2 回答 2

0

您可以按如下方式检索莫斯科的当地时间:

// Get a DateTimeFormat object for the hour in Moscow in 24-hour format
const dtf = Intl.DateTimeFormat('en', {
  timeZone: 'Europe/Moscow',
  hour: 'numeric',
  hour12: false
});

// The above will create a format that has only the hour, so you can just use it.
const hour = +dtf.format();

console.log("hour:", hour);

或者,如果您决定需要的不仅仅是一小时,请使用formatToParts. 例如:

const dtf = Intl.DateTimeFormat('en', {
  timeZone: 'Europe/Moscow',
  hour: 'numeric',
  hour12: false,
  minute: 'numeric'
});

const parts = dtf.formatToParts();
const hour = +parts.find(x => x.type === 'hour').value;
const minute = +parts.find(x => x.type === 'minute').value;

console.log("hour:", hour);
console.log("minute:", minute);

然后,您可以根据需要在其余代码中使用它。

于 2020-06-18T18:12:45.747 回答
0

我在这里找到了解决方案:在此处输入链接描述我需要执行以下操作:

function calcTime() {
  const now = new Date();
  const utc = now.getTime() + (now.getTimezoneOffset() * 60000);

  const d = new Date(utc + (3600000 * 3));
  const h = d.getHours();
  const dtfRU = new Intl.DateTimeFormat('ru', {
    month: 'long', day: '2-digit',
  });

  if (h >= 15) {
    const newd = new Date(utc + (3600000 * 3 * 9));
    document.querySelector('.date').innerHTML = dtfRU.format(newd);
  } else document.querySelector('.date').innerHTML = dtfRU.format(d);
}
document.addEventListener("DOMContentLoaded", calcTime);
于 2020-06-19T07:35:56.550 回答