1

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.

Leo
  • 15
  • 3
  • A JavaScript `Date` is the number of milliseconds since Jan 1, 1970 in the UTC timezone. The internal timezone cannot be changed from UTC. Do your manipulation however you like and just output the result in the selected locale as shown. Note that a lot of methods of the `Date` object output values in the local timezone, so check the API reference for methods you decide to use. – Tibrogargan Aug 05 '19 at 06:16
  • This might help with determining difference between two dates: [Difference between dates in JavaScript](/questions/1968167/difference-between-dates-in-javascript) – Tibrogargan Aug 05 '19 at 06:17
  • Thanks for the clarification and the url guys, it'll help a lot. – Leo Aug 06 '19 at 02:20

1 Answers1

0

You can use moment.js functions for all your problems.

  1. If your event times in any specific timezone(s), first of all convert them to utc value. moment.utc()
  2. When user connect to your page, get his/her time in utc. moment.valueOf()
  3. Calculate duration between 2 dates. moment.duration, moment.diff
  4. Format duration how do you want. duration-format
Murat Aras
  • 403
  • 2
  • 10
  • I will try and do this with just vanilla js, but if I can't for any reason I'll check it out for sure. Thanks, pal. – Leo Aug 06 '19 at 02:25