如何不使用系统时间获取Javascript中的当前日期/时间?

时间:2020-09-16 06:58:17

标签: javascript

new Date()获取当前系统时间。这意味着,如果当前系统时间错误(在我的情况下,客户端计算机是Windows系统,其时间设置为当前时间的-4小时),则new Date()将提供错误的值。

我需要一种方法来获取客户端的当前日期/时间而不使用他的机器日期/时间(可能是某种方法来确定客户端所坐的时区并进而确定时间)。

如何在JS中做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以从Internet上的API中获取时间,从而不必使用客户端时间。您可以在以下网站上提出API请求以获取时间。希望对您有所帮助。

https://worldtimeapi.org/

下面是一个示例,您如何从上述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 resolvedoptionsfetch的工作示例

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));

相关问题