5

I have the following code to get (timestamp) and (NOW timestamp). I subtract them to get the difference between them but I get a number like 123456 and I can not understand how much this number represent. I want to check if the difference between those two dates are less than one hour, how?

final_time = new Date(2013, 11, 11, 11, 11);
c_date = new Date();
offset_time = c_date.getTimezoneOffset();
var n1 = Math.abs(offset_time);
current_date = new Date(c_date.getTime() - n1 * 60 * 1000);

alert(current_date-final_time);
Basel
  • 1,305
  • 7
  • 25
  • 34
  • running your code gives ...2598440754 milis is 721 hours. (if swapping over the subtration at the end to give a positive number, c_date.getTime() - final_time.getTime()). Just take that and work out if that is greater than '60 * 60 * 1000'. Just see 'codebox's answer below, its more eloquent than my comment. – jeff porter Nov 11 '13 at 10:16

2 Answers2

8

You can get the difference between the two dates in milliseconds if you do:

var diffInMillis = c_date.getTime() - final_time.getTime()

To find out if this is less than 1 hour you can do this:

var isLessThan1Hour = diffInMillis < 60 * 60 * 1000;
codebox
  • 19,927
  • 9
  • 63
  • 81
  • but does it affect dates? i mean if i want to subtruct two dates ? this code work for today dates with different hour times but does it work for two different dates?? – Basel Nov 11 '13 at 10:09
  • yes, the getTime() method is confusingly named - its gets the number of milliseconds between midnight of January 1, 1970 and the specified date and time – codebox Nov 11 '13 at 10:11
  • can u please tell me what the 1000 represent?? – Basel Nov 11 '13 at 10:19
  • 1000 converts seconds into milliseconds. 60 * 60 * 1000 gives you the number of milliseconds in 1 hour – codebox Nov 11 '13 at 10:21
  • sorry but each time I alert the isLessThan1Hour it gave me a false, even i set a date with one minute difference can u check this please? – Basel Nov 11 '13 at 10:23
0

Instead of directly subtracting the timestamps try to diff the dates from which you can individually get hours.From then on one can do a simple maths to do the difference.

That's a more clear and maintainable approach