user712092
user712092

Reputation: 1986

Why doesn't this method for getting the difference between two dates work?

I am trying to test whether certain time has elapsed. I use javascript.

Both examples use this variable:

var delete_after = 2 /*minutes*/ * 60 /*seconds*/ * 1000/*miliseconds*/; // [miliseconds]

This works:

var now = new Date();
var now_t = now.getTime();
var then = new Date(x.time); // x.time is string with a time
var then_t = then.getTime();//).getTime();
if (now_t - then_t > delete_after) {
    alert("deleted");
}

This does not:

if (Date().getTime() - Date(x.time).getTime() > delete_after) {
    alert("deleted");
}

I belived them to be equivalent, but they are not. I checked precedence, in the end it appears I have to call new to create a variable. It seems to impossible to call (new Date().getTime()). Please, would You be so kind to explain why it can not be written the second way?

Upvotes: 0

Views: 556

Answers (3)

spike
spike

Reputation: 10004

getTime is a function of date objects, not of the Date() function, so you have to call Date() to get a date object, and then call getTime on it.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

This would do it all in one go, but it's a bit confusing

(new Date()).getTime()

Upvotes: 2

Rok Kralj
Rok Kralj

Reputation: 48755

Well, if you want to do it in short, just do it like this:

if ((new Date()).getTime() - (new Date(x.time)).getTime() > delete_after) {
    alert("deleted");
}

Your example didn't work because object has to be instantiated before you perform any function call on it.

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

  • Date().getTime()

    is not the same as

    (new Date()).getTime()


  • Date(x.time).getTime()

    is not the same as

    (new Date(x.time)).getTime()

Upvotes: 5

Related Questions