简体   繁体   中英

How can I calculate the difference between two times that are in 24 hour format which are in different dates?

In JavaScript, how can I calculate the difference between two times that are in 24 hour format which are having different dates?

Example: Date1 is 2019/12/31 11:00:06 AM Date2 is 2020/01/01 01:10:07 PM. Time difference should be 02:10:13 in hh:MM:ss format ..how can get like this when date changes in appscript

Just use the Date

const dateDiffMs = (date1,date2 ) => {
    const d1 = new Date(date1);
    const d2 = new Date(date2);
    return d1.getTime() - d2.getTime()
}

const ms2hms = (ms) => {
    const sec = Math.floor(ms / 1000)
    const min = Math.floor(sec / 60)
    const h = Math.floor(min / 60)

    return [
        h,
        min % 60,
        sec % 60,
    ];
};

const format = (n) => n < 10 ? '0' + n : n;

const hms2str = ([h, min, sec]) => {
    return `${h}:${format(min)}:${format(sec)}`
}

alert(hms2str(ms2hms(dateDiffMs('2020/01/01 01:10:07 PM', '2019/12/31 11:00:06 AM')))); // 26:10:01

This code works correctly if both date1 and date2 are in the same timezone. But i would recommend you to use moment.js or some other library

I would do this by gathering the date in second since whenever computers decided to keep track of time for us sometime in the 70's (epoch). Then pass it the second value and subtract, leaving the difference.

You would then need to convert it back to a date format I presume:

 (function(){ var dateOneSeconds = new Date().getTime() / 1000; setTimeout(function(){ var dateTwoSeconds = new Date().getTime() / 1000; var seconds = dateTwoSeconds - dateOneSeconds; console.log(seconds); var timeDifferenceInDate = new Date(seconds * 1000).toISOString().substr(11, 8); console.log(timeDifferenceInDate); }, 3000); })();

NOTE: I have used a timeout function - you will already have two dates that do not match to pop in.

EDIT: having been notified the days will not be calculated, you could maybe use date to calculate your time in seconds then use Math to create your display:

 (function(){ var dateOneSeconds = new Date().getTime() / 1000; setTimeout(function(){ var dateTwoSeconds = new Date().getTime() / 1000; var seconds = dateTwoSeconds - dateOneSeconds; console.log(seconds); /* var timeDifferenceInDate = new Date(seconds * 1000).toISOString().substr(11, 8); */ seconds = Number(seconds); var d = Math.floor(seconds / (3600*24)); var h = Math.floor(seconds % (3600*24) / 3600); var m = Math.floor(seconds % 3600 / 60); var s = Math.floor(seconds % 60); timeDifferenceInDate = d + ':' + h + ':' + m + ':' + s; console.log(timeDifferenceInDate); }, 3000); })();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM