1

Okay so what i'm trying to do is get the time values between 2 different dates.

For example:

date1 = 3/2/2014 - 14:12

date2 = 4/2/2014 - 16:22

How would I get the time difference between date1 and date2? (26hrs, 10mins) <- that would be the perfect output for what I want.

I've had a look at the parse method and if I understand it correctly, I think I could make that work by doing something like:

myDate = date1;

myDate.parse(date2);

then convert the output to how I wanted it from there, but I haven't seen any examples where it takes the time of day into consideration.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
user3238415
  • 188
  • 1
  • 11
  • Possible duplicate of [Compare two dates with JavaScript](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) –  Aug 02 '17 at 14:45

2 Answers2

0

You could use the Date class and then just subtract the 2 dates

var difference = ( new Date(2014, 2, 4, 16, 22, 0).getTime()
                   - new Date(2014, 2, 3, 14, 12, 0).getTime()
                 ) / 1000

getTime() gives you the time in milliseconds, so you have to divide by 1000 to get the result in seconds.

Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
0

You just need to subtract the two Date object to get the difference since JavaScript will convert it to the right type automatically:

date1 - date2  //difference in milliseconds

For formatting, you can set up a function similar to this:

Number.prototype.format = function(){
    return [
        (this/86400|0), "days",
        (this/3600|0) % 24 , "hours",
        (this/60|0) % 60 , "minutes",
        (this|0) % 60 , "seconds"
    ].join(" ");
};

((date1 - date2)/1000).format();  //Formatted string

Demo: http://jsfiddle.net/DerekL/Prb7j/ (Time formatting also included)

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247