Skip to content Skip to sidebar Skip to footer

How To Get Current Date/time In Javascript Without Using System Time?

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

Solution 1:

Working example using intl resolvedoptions and 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));

One using user's IP

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

Solution 2:

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.org/

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.org/api/ip",
    success: function(result) {
      console.log(result)
      $("#tm").text(result.datetime);
    }
  });
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><inputid="btn"type="button"value="Get Current Time" /><pid="tm" />

Post a Comment for "How To Get Current Date/time In Javascript Without Using System Time?"