0

I am trying to get a difference in Month, Date, Hour, Minute and Second between two dates in JavaScript.

I know that we can get a date difference in millisecond and already tried as follows:

function showtime() {
    var date1 = new Date('7/14/2010 6:21:00');
    var date2 = new Date('12/15/2010 7:25:10');
    var diffTime = parseInt(date2 - date1);
    var diffMonth = Math.floor(diffTime / (1000 * 60 * 60 * 24 * 30));
    var diffDays = Math.floor((diffTime / (1000 * 60 * 60 * 24)) - (diffMonth * 30));
    var diffHour = Math.floor((diffTime / (1000 * 60 * 60)) - (diffMonth * 30 * 24) - (diffDays * 24))
    var diffMinute = Math.floor((diffTime / (1000 * 60)) - (diffMonth * 60 * 30 * 24) - (diffDays * 60 * 24) - (diffHour * 60))
    var diffSec = Math.floor((diffTime / (1000)) - (diffMonth * 60 * 60 * 30 * 24) - (diffDays * 60 * 60 * 24) - (diffHour * 60 * 60) - (diffMinute * 60))

    var result = (diffMonth + ' Month ' + diffDays + ' Days ' + diffHour + ' Hours ' + diffMinute + ' Minutes ' + diffSec + ' Sec' );

    return result;
}

But the above function cannot calculate the exact days and months. Any help would be appreciated.

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
Pawan Gupta
  • 177
  • 8

2 Answers2

0

You are making an assumption that all months have only 30 days, while it isn't (diffMonth uses 30 days multiplier) - this will skew the Number of Days

Naren
  • 797
  • 13
  • 12
  • yes that is only the reason why this question is given. – Pawan Gupta Feb 29 '20 at 13:42
  • The question wasn't exactly clear on what was needed, hence I pointed out why the Number of Days could be skewed. However, calculating No.Of Months w/ No.Of Days is subject to quite a few different scenarios i.e. if it a Leap Year, does the month have 30 or 31 days. I think checking these questions could help you and see if you can build upon it - https://stackoverflow.com/questions/2536379/difference-in-months-between-two-dates-in-javascript & https://stackoverflow.com/questions/17732897/difference-between-two-dates-in-years-months-days-in-javascript – Naren Mar 03 '20 at 12:21
0

Please try my code :

let duration = Math.abs(date1 - date2) / 36e5;
let totalDuration = Math.round(duration * 10) / 10;

totalDuration = totalDuration.toString().replace('.', 'H : ') + 'M';
// 13H : 2M