1

I have 2 dates to which I am counting down from one to the other. I am using the moment library. I have found this answer here but it is not giving me the correct result.

The following code gives me the times below:

var eventTime =  new Date(startTime);
var currentTime =  new Date();

console.log(eventTime);
console.log(currentTime);

Fri Feb 24 2017 19:45:00 GMT+0000 (GMT) --> eventTime

Tue Feb 21 2017 08:42:42 GMT+0000 (GMT) --> currentTime

I have tried many varieties of the following,but cannot display the correct countdown time.

var eventTime = new Date('2017-02-24T19:45:00.000000+0000').getTime();
var currentTime = new Date().getTime()

console.log(eventTime);
console.log(currentTime)

var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime * 1000, 'milliseconds');
var interval = 1000;

setInterval(function() {
  duration = moment.duration(duration - interval, 'milliseconds');
  console.log(duration.days() + ':' + duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
Community
  • 1
  • 1
peter flanagan
  • 9,195
  • 26
  • 73
  • 127
  • @VincenzoC click on run code snippet a number of times and you will see the value keeps changing and is not consistent... for example it currently says the event is 29 days away for me... im guessing im making an error on obtaining the `ms` or something like that – peter flanagan Feb 21 '17 at 08:59

1 Answers1

2

.getTime() already returns milliseconds, no need to multiply it by 1000.

You have to change this line to this

var duration = moment.duration(diffTime * 1000, 'milliseconds');

to this

var duration = moment.duration(diffTime, 'milliseconds');
arc
  • 4,553
  • 5
  • 34
  • 43