I want to build a webpage with some JavaScript which will count the days, hours, minutes and seconds between two events (now and LastTime). My issue is: I'm using this line var now = new Date().getTime();
to get the present time, and it looks like this method uses your machine settings to get the now
variable, which is undesired because if a person outside my region access the page, the counter won't show the real time past since my JavaScript is getting theirs time zone.
I found some piece of code on the internet that actually gets the time from a given region, but I'm struggling to integrate into my code.
var now = new Date().toLocaleString("pt-BR", {timeZone: "America/Sao_Paulo"});
now = new Date(now);
<h1>Time past since the last event: </h1>
<h2 id="demo"></h2>
<script>
var lastTime = new Date("July 27, 2019 00:00:00").getTime();
setInterval(function() {
var now = new Date().getTime();
var distance = now - lastTime;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("demo").innerHTML = days + " days, " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds ";
}, 1000);
</script>
What I want is my now
variable to get a especific region time ('America/New_York' for example) and make the counter do right math wherever region my page is accessed. Here's some codepen to make it easier.
Thanks in advance.