how can I get a list of all countries together with their time using moment js?

Viewed 324
 const timezone = moment.tz.names();
  const timezoneList = [];

  timezone.forEach((element) => {
    timezoneList.push({ label: element, value: element });
  });

At the moment I am just getting the list but I am trying to get also the local time of each country together.

Thank you very much

1 Answers

I'd suggest having a look at countries-and-timezones, this has a very convenient list of countries along with their timezones.

Once we have a country's list of timezones we can get the local time(s), using Date.toLocaleTimeString() allowing us to log local times for each country.

I've done this for the first 20 countries below:

let countries = Object.values(ct.getAllCountries()).sort(({ name: a}, { name: b}) => a.localeCompare(b)).slice(0,20);
console.log('Country'.padEnd(20), 'Local Time(s):')

for(let country of countries) {
    console.log(country.name.padEnd(20), getLocaleTimes(country.timezones).join(", "))
}

function getLocaleTimes(timeZones) {
    return [...new Set(timeZones.map(getLocalTime))];
}

function getLocalTime(timeZone) {
    return new Date().toLocaleTimeString([], { timeZone, });
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdn.jsdelivr.net/gh/manuelmhtr/countries-and-timezones@latest/dist/index.min.js" type="text/javascript"></script>

Related