js calculates the difference between two date and time

1. Calculate the difference between the two times: 

    let date1 = new Date('2020-12-02 12:30:54')
    let date2 = new Date('2020-12-02 15:38:09')
 
    let s1 = date1.getTime(),s2 = date2.getTime();
    let total = (s2 - s1)/1000;
 
    let day = parseInt(total / (24*60*60));//计算整bai数天du数
    let afterDay = total - day*24*60*60;//取得值算出天数后dao剩余的转秒数shu
    let  hour = parseInt(afterDay/(60*60));//计算整数小时数
    let afterHour = total - day*24*60*60 - hour*60*60;//取得算出小时数后剩余的秒数
    let min = parseInt(afterHour/60);//计算整数分
    let afterMin = total - day*24*60*60 - hour*60*60 - min*60;//取得算出分后剩余的秒数

//  console.log('day',day)
//  console.log('afterDay',afterDay)
//  console.log('hour',hour)
//  console.log('afterHour',afterHour)
//  console.log('min',min)
//  console.log('afterMin',afterMin)
 let hous=(afterDay/3600).toFixed(2)//截取小数点后两位.toFixed(2)

2. Supplementary explanation

What we need to pay attention to is the date format. If we use the '2020-12-03' date format, there will be a problem of calculating the value of NaN on ios, and Android is no problem, this needs to be changed to '2020/12/ 03' format date format

time = time.replace(/-/g, '/')

 

Guess you like

Origin blog.csdn.net/asteriaV/article/details/110525756