-2

This is a very common question, however I wasn't able to find a correct answer. I have the following:

tcom
Mon Dec 14 2015 12:22:28 GMT-0500 (PET)
treq
Mon Dec 14 2015 12:18:27 GMT-0500 (PET)

tcom - treq
241122
tdif = new Date(tcom - treq);
Wed Dec 31 1969 19:04:01 GMT-0500 (PET)

I've seen answers like this:Get difference between 2 dates in javascript? but that is a fixed method, I don't know beforehand if the difference is going to be days, hours, minutes or seconds.

Thanks

Community
  • 1
  • 1
PepperoniPizza
  • 8,842
  • 9
  • 58
  • 100
  • `tcom - treq` <--- this is the difference between 2 dates. Anything wrong with it? – zerkms Dec 15 '15 at 02:25
  • 1
    Well, `241122` ms *is* the difference between those two datetimes. What exactly are you asking for? – Bergi Dec 15 '15 at 02:25
  • 1
    duplicate of http://stackoverflow.com/q/17732897/1048572, http://stackoverflow.com/q/18623783/1048572 or some other – Bergi Dec 15 '15 at 02:29

3 Answers3

0

You are returned with a difference in miliseconds, so do some math calc here. 1 day = 24 x 60 x 60 x 10 = 864000 miliseconds.

Cashmirek
  • 269
  • 1
  • 9
0

Yes, subtracting two Date objects is a correct way to find their difference in milliseconds.

The following are equivalent:

date1 - date2
date1.getTime() - date2.getTime()

If you want to convert the result to years, months, days, etc., you can create a new Date object at epoch with the millisecond part set to the offset that you've obtained. e.g.:

var start = new Date();

// some time passes...

var end = new Date();

var elapsedMillis = end - start;

var elapsed = new Date(1970, 0, 1, 0, 0, 0, elapsedMillis);

Then you can use methods like getMinutes(), getSeconds() etc. to get the components you want.

Ates Goral
  • 137,716
  • 26
  • 137
  • 190
0

If you're trying to get the difference in a number of different units, you can use a function that takes an enumerated value, like:

var Units = {
    MS: 1,
    SEC: 1000,
    MIN: 1000 * 60,
    HOUR: 1000 * 60 * 60,
    DAY: 1000 * 60 * 60 * 24,
    YEAR: 1000 * 60 * 60 * 24 * 365
};

function getDateDiff( a, b, unit ) {
    return (a - b) / unit;
}

Then you can call it easily:

getDateDiff( date1, date2, Units.HOUR );

If you only need it in ms though, then a simple subtraction is your best friend.

TbWill4321
  • 8,626
  • 3
  • 27
  • 25