new Date()
获取当前系统时间。这意味着,如果当前系统时间错误(在我的例子中,客户端计算机是Windows系统,其时间设置为当前时间的-4小时),new Date()
将提供错误的值。
我需要一种方法来获取客户端的当前日期/时间,而不使用他的机器日期/时间(可能是某种方法来找出客户端所在的时区,进而找出时间)。
我如何在 JS 中做到这一点?
工作示例使用国际解决选项 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/resolvedOptions and fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
fetch("https://worldtimeapi.org/api/timezone/"+tz)
.then(response => response.json())
.then(data => console.log(tz,data.dst,data.datetime));
一个使用用户的IP
fetch("https://worldtimeapi.org/api/ip")
.then(response => response.json())
.then(data => console.log(data.dst,data.datetime));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)