R
R
Recreator2020-05-22 13:27:06
JavaScript
Recreator, 2020-05-22 13:27:06

How to calculate time from JSON knowing difference from UTC?

Hello!
I decided to make a quick guide to countries here and collected JSON. The data in it looks like this:

...
{
    "country": "Sri Lanka",
    "phoneCode": "+94",
    "capital": "Colombo",
    "abbr": "LKA",
    "population": "21413249",
    "code": "LK",
    "currency": "LKR",
    "timezones": "UTC+05:30"
  }
...

I output them with a script:
const outputHtml = (fits) => {
  if (fits.length > 0) {
    const html = fits
      .map(
        (fit) => `
          <div class="card">
            <div class="card-top">
              <div class="card-title">${fit.country}</div>
              <img src="./img/flags/${fit.code}.svg">
            </div>
            <div class="card-data">
              <div>Population: ${fit.population.replace(/\B(?=(\d{3})+(?!\d))/g, ' ')}</div>
              <div class="capitalCity">Capital: <span class="capitalName">${fit.capital}</span>
                <div id="capitalWeather"></div>
              </div>
              <div>Country Code: ${fit.phoneCode}</div>
              <div class="currency">Сurrency: <span>${fit.currency}</span>
                <div id="currencyData"></div>
              </div>
              <div>Time: ${fit.timezones}</div>
            </div>
          </div>
        `
      )
      .join('');
    document.getElementById('countryList').innerHTML = html;
  }
};

Question: how to calculate the current time in different cities, knowing your time in UTC and the difference in the city's time from UTC (including the difference in minutes)?
As a result, now it looks like this, but every time it’s probably not very convenient to recalculate the time in your mind:
5ec7a853e2566810381095.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-05-22
@Recreator

play around with possible timezones

function offsetToMs(s) {
  const [h, m] = s.replace(/utc/i, '').split(':').map(x => Number(x.replace(/\D/, '')))
  const ms = (h * 60 * 60 * 1000) + (m * 60 * 1000)
  return s.includes('-') ? -ms : ms
}

off = offsetToMs("UTC+05:30")
console.log( new Date(new Date().getTime() + off) )

UPD
ok, this just adds an offset to the browser time, but if "knowing your time in UTC", then you can fix it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question