functionconvertStrToDate(dateStr) { let ary = dateStr.split(" "); let d = ary[0].split("/"); let t = ary[1].split(":"); returnnewDate(d[0], d[1] - 1, d[2], t[0], t[1], t[2], 00); }
functiondateDiff(start, end) { constleftPad = num => (num > 9 ? num : "0" + num); let diffMs = end - start; // 取得兩日期相差的毫秒數 let diffDays = Math.floor((diffMs / 86400000)); // 取得天數 let diffHrs = Math.floor((diffMs % 86400000) / 3600000); // 取得小時數 let diffMins = Math.floor(((diffMs % 86400000) % 3600000) / 60000); // 取得分鐘數 let diffSecs = Math.floor((((diffMs % 86400000) % 3600000) % 60000) / 1000); // 取得秒數 returnleftPad(diffHrs) + ":" + leftPad(diffMins) + ":" + leftPad(diffSecs); }
實務上就可以直接透過這樣的方式進行計算,取得兩個日期的差異結果了
1 2 3
let startTime = convertStrToDate("2019/08/21 15:30:00"); let endTime = convertStrToDate("2019/08/23 16:55:05"); let result = dateDiff(startTime, endTime) // 01:25:05