0

I'm trying to calculate time locally on the client machine to specify the ending time of a certain promotion. I do so by using the following code:

var targetDate = new Date(1442055673000);
var currentDate = new Date;
setInterval(updateTime, 1000);
function updateTime() {
  var diff = new Date(targetDate - new Date());
  var days = diff.getUTCDay();
  var hours = diff.getUTCHours();
  var minutes = diff.getUTCMinutes();
  var seconds = diff.getUTCSeconds();
  console.log(days + " : " + hours + " : " + minutes + " : " + seconds);}

The date at which the promotion ends is 09.12.2015 and today is 09.09.2015. For whatever reason the difference is calculated incorrectly (it shows that the difference is 6 days instead of 3).

Dronich
  • 195
  • 1
  • 3
  • 10
  • 1
    In addition to Andrey's response, this question might be helpful: http://stackoverflow.com/questions/2627473/how-to-calculate-the-number-of-days-between-two-dates-using-javascript – Marc Sep 09 '15 at 17:50
  • You're constructing a date from the difference of 2 timestamps, which isn't what you expect it to be. – Joseph Sep 09 '15 at 17:51

1 Answers1

0

The getUTCDay() method returns the day of the week in the specified date according to universal time, where 0 represents Sunday.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDay

You are creating date from date differences, which is very bad representation for date difference. The easiest way to get number of days, hours and the rest is just use integer division:

  var diff = Math.floor(new Date(targetDate - new Date()) / 1000);
  var days = Math.floor(diff / (60*60*24)); 
  diff %= 60*60*24;
  var hours = Math.floor(diff / (60*60));
  diff %= 60*60;
  var minutes = Math.floor(diff / (60));
  diff %= 60;
  var seconds = diff;
Andrey
  • 59,039
  • 12
  • 119
  • 163