每次时钟为 1:1 或更多时,我需要将莫斯科时间的当前日期增加 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);
我在这里找到了一个解决方案:在此处输入链接描述 我需要做这样的事情:
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);
您可以按如下方式检索莫斯科的当地时间:
// 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);
然后,您可以根据需要在其余代码中使用它。