Convert the local time to another time zone with this JavaScript

349 views Asked by At

I need to increase the current date in Moscow time by 1 day every time the clock is 15:00 and more. I did it at local time, but I can’t do it according to Moscow time (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);

2

There are 2 answers

3
Matt Johnson-Pint On

You can retrieve the local hour in Moscow as follows:

// 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);

Alternatively, if you decide you need more than just the hour, use formatToParts. For example:

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

You can then use that in the rest of your code however you wish.

0
Vladislav On

I found a solution here: enter link description here I needed to do something like this:

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