为了做到这一点,不利用IP-地点服务,以下代码利用<条码——实时条码”的图书,用于绘制各国的时间区。 如果规定的时间区与任何一国有关,则该职能通过国家名单和核对表公布。 如果找到了对应办法,则使用<条码
// Import the moment-timezone library
const moment = require( moment-timezone );
/**
* Get the user s country based on their time zone.
* @param {string} userTimeZone - The user s time zone.
* @returns {string} The user s country or the original time zone if not found.
*/
function getCountryByTimeZone(userTimeZone) {
// Get a list of countries from moment-timezone
const countries = moment.tz.countries();
// Iterate through the countries and check if the time zone is associated with any country
for (const country of countries) {
const timeZones = moment.tz.zonesForCountry(country);
if (timeZones.includes(userTimeZone)) {
// Use Intl.DisplayNames to get the full country name
const countryName = new Intl.DisplayNames([ en ], { type: region }).of(country);
return countryName;
}
}
// Return the original time zone if no matching country is found
return userTimeZone;
}
// Example usage
const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const userCountry = getCountryByTimeZone(userTimeZone);
console.log( User country based on time zone: , userCountry);
Usage:
- Copy and paste the provided code into your JavaScript environment.
- Call the getCountryByTimeZone function with the user s time zone to retrieve the user s country.
- The function returns either the matching country or the original time zone if no match is found.
Note:
- Make sure to have the moment-timezone library installed in your project.
- The accuracy of the result depends on the completeness and accuracy of the time zone data provided by the library.