new Date()
获取当前系统时间。这意味着,如果当前系统时间错误(在我的情况下,客户端计算机是Windows系统,其时间设置为当前时间的-4小时),则new Date()
将提供错误的值。>
我需要一种方法来获取客户端的当前日期/时间而不使用他的机器日期/时间(可能是某种方法来确定客户端所坐的时区并进而确定时间)。
如何在JS中做到这一点?
答案 0 :(得分:2)
您可以从Internet上的API中获取时间,从而不必使用客户端时间。您可以在以下网站上提出API请求以获取时间。希望对您有所帮助。
下面是一个示例,您如何从上述API中基于IP地址获取时区。
注意:请访问上面的链接以获取您所需时区的API链接,并在此处提供。
$("#btn").on("click", function() {
$.ajax({
url: "https://worldtimeapi.org/api/ip",
success: function(result) {
console.log(result)
$("#tm").text(result.datetime);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="btn" type="button" value="Get Current Time" />
<p id="tm" />
答案 1 :(得分:2)
使用intl resolvedoptions和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));