Bas
Bas

Reputation: 2210

Calculating the amount of seconds between 2 dates in javascript

I've been looking around to learn how to calculate the time between 2 certain dates: the date right now, and the date we are calculating from.

I found this snippet and edited it abit to my needs:

function dateDiffInDays(a, b) {
    var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours(), a.getMinutes(), b.getSeconds());
    var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate(), b.getHours(), b.getMinutes(), b.getSeconds());

    return Math.floor((utc2 - utc1) / 1000);
}

It calculates the amount of seconds between 2 dates.

This method is getting called by this piece of code:

var j = new Date('July, 05, 2012');
var n = new Date();

setInterval(function () {
    document.getElementById("b").innerHTML = dateDiffInDays(j, n);
}, 1000)

What is that it is auto updating every second, wich i thought i did with the setInterval method. Why is'nt this working?

Also, whenever i re-run the code, it doesnt even update the number.

Demo here

Upvotes: 0

Views: 111

Answers (3)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

Here's the correct version:

var j = new Date('July, 05, 2012');
setInterval(function () {
    var n = new Date();
    document.getElementById("b").innerHTML = dateDiffInDays(j, n);
}, 1000);

n was never updated in your code.

j is left alone because its value is constant. But I moved n inside the periodical function so it gets a new value at each period.


Oh, and you made an error on this line:

var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours(), a.getMinutes(), b.getSeconds());

That should be:

var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours(), a.getMinutes(), a.getSeconds());

Upvotes: 3

Mithun Satheesh
Mithun Satheesh

Reputation: 27835

please check this out if you are looking for a working fiddle.

I have updated the code a bit as I dint understand the need of re creating the date objects inside the function when you have them passed as function parameters.

setInterval(function () {
    var n = new Date();
    document.getElementById("b").innerHTML = dateDiffInDays(j, n);
}, 1000)

var j = new Date('July, 05, 2012');

// a and b are javascript Date objects then why are you re creating the date objects again?
function dateDiffInDays(a, b) {
    var _MS_PER_DAY = 1000;
    return Math.floor((b.getTime() - a.getTime()) / _MS_PER_DAY);
}

Upvotes: 1

WORMSS
WORMSS

Reputation: 1664

Because n is not being recreated, so you are saying how many seconds from the date you specified, and the date that the n variable was created. Use:

setInterval(function () {
    document.getElementById("b").innerHTML = dateDiffInDays(j, new Date());
}, 1000)

Upvotes: 2

Related Questions