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
2 Answers
Reset to default 6Working 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" />