2017-04-26 95 views
4

我希望我的网页在用户的语言环境中显示日期和时间。Javascript - 使用Intl获取当前语言环境以显示时间和日期

现在大多数浏览器似乎都支持Intl(请参阅Can I Use Intl)。我可以通过使用Intl.DateTimeFormat().resolvedOptions().timeZone来获得浏览器时区。我希望我能够用我的当前区域发射日期时间,通过做:

var date = new Date(2017, 11, 31, 23, 59, 59); 
 
var format = new Intl.DateTimeFormat(
 
    undefined, // locale 
 
    { 
 
    year: "numeric", 
 
    month: "numeric", 
 
    day: "numeric", 
 
    hour: "numeric", 
 
    minute: "numeric", 
 
    } 
 
) 
 

 
console.log(format.format(date))

我在Windows上使用Chrome。我的Windows操作系统区域设置设置为“捷克共和国”。我的首选网站语言在Chrome中设置为“捷克语”,但浏览器本身设置为使用美国英语。

使用这些设置,输出以12 H格式完成,就好像我的语言环境为en-us。只要我将Chrome浏览器切换为使用捷克语作为其演示语言,时间就会切换为24格式。

我认为我必须丢失一些明显的东西 - 网页真的无法使用区域设置用户正在使用,还是这是Chrome Intl实施中的一些错误或不完整?

回答

0

我发现以下在Chrome上更可靠:可以使用navigator.languages[0]来获取用户喜欢的内容所使用语言定义的语言环境。有关浏览器兼容性的讨论,另请参阅Best way to determine user's locale within browser

function getLocale() { 
 
    return (navigator.languages && navigator.languages.length) ? navigator.languages[0] : navigator.language; 
 
} 
 

 

 
var locale = getLocale(); 
 
var date = new Date(2017, 11, 31, 23, 59, 59); 
 
var format = new Intl.DateTimeFormat(
 
    locale, 
 
    { 
 
    year: "numeric", 
 
    month: "numeric", 
 
    day: "numeric", 
 
    hour: "numeric", 
 
    minute: "numeric", 
 
    } 
 
) 
 

 
console.log(format.format(date))

不过这似乎是一个耻辱一个无法访问系统广泛的选择区域的用户做出。

相关问题