如何使用 moment js 获取所有国家的列表及其时间?
how can I get a list of all countries together with their time using moment js?
const timezone = moment.tz.names();
const timezoneList = [];
timezone.forEach((element) => {
timezoneList.push({ label: element, value: element });
});
目前我正在获取列表,但我正在尝试同时获取每个国家/地区的当地时间。
非常感谢
我建议看看 countries-and-timezones,它有一个非常方便的国家列表及其时区。
一旦我们有了一个国家的时区列表,我们就可以得到当地时间,使用
Date.toLocaleTimeString() 允许我们记录每个国家/地区的当地时间。
我已经为以下前 20 个国家/地区完成了此操作:
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>
const timezone = moment.tz.names();
const timezoneList = [];
timezone.forEach((element) => {
timezoneList.push({ label: element, value: element });
});
目前我正在获取列表,但我正在尝试同时获取每个国家/地区的当地时间。
非常感谢
我建议看看 countries-and-timezones,它有一个非常方便的国家列表及其时区。
一旦我们有了一个国家的时区列表,我们就可以得到当地时间,使用 Date.toLocaleTimeString() 允许我们记录每个国家/地区的当地时间。
我已经为以下前 20 个国家/地区完成了此操作:
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>