最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to get current datetime in Javascript without using system time? - Stack Overflow

programmeradmin2浏览0评论

new Date() fetches the current system time. This means, if the current system time is wrong (in my case, the client machine was a Windows system, whose time was set to -4 hours of the current time), new Date() will provide a wrong value.

I need a way to get current Date/time of the client without using his machine date/time (probably some way to figure out the timezone where the client is sitting and in turn figure out the time).

How do I do this in JS?

new Date() fetches the current system time. This means, if the current system time is wrong (in my case, the client machine was a Windows system, whose time was set to -4 hours of the current time), new Date() will provide a wrong value.

I need a way to get current Date/time of the client without using his machine date/time (probably some way to figure out the timezone where the client is sitting and in turn figure out the time).

How do I do this in JS?

Share Improve this question asked Sep 16, 2020 at 6:58 Scary TerryScary Terry 2271 gold badge3 silver badges15 bronze badges 2
  • How is a client's system time "wrong" just because it's in another timezone? Are you just asking how to get the current time in a specific timezone? – Cully Commented Sep 16, 2020 at 7:01
  • Yes. being in another timezone is not an issue. I need the correct time of that timezone. – Scary Terry Commented Sep 16, 2020 at 7:05
Add a ment  | 

2 Answers 2

Reset to default 6

Working example using intl resolvedoptions and fetch

const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;

fetch("https://worldtimeapi/api/timezone/"+tz)
  .then(response => response.json())
  .then(data => console.log(tz,data.dst,data.datetime));

One using user's IP

fetch("https://worldtimeapi/api/ip")
  .then(response => response.json())
  .then(data => console.log(data.dst,data.datetime));

You can get time from an API that is on internet, that way you don't have to use client time. The following website where you can make API request to get a time. I hope it helps.

https://worldtimeapi/

Here's an example how you can get Timezone based on your IP address from the above API.

Note: Please visit the link above to get API link for the timezone you need and provide here.

$("#btn").on("click", function() {
  $.ajax({

    url: "https://worldtimeapi/api/ip",
    success: function(result) {
      console.log(result)
      $("#tm").text(result.datetime);
    }
  });
});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input id="btn" type="button" value="Get Current Time" />
<p id="tm" />

发布评论

评论列表(0)

  1. 暂无评论