计算时间差工具类(TypeScript/JavaScript)
const time = ["2022-08-20 15:19:00","2022-08-20 13:19:00","2022-08-20 16:19:22"] //比较两个时间相差的小时 function compareTime(time1:string,time2:string){ //转换为Date let date1:Date = new Date(time1); let date2:Date = new Date(time2); console.log(date1); console.log(date2); //计算时间差的毫秒数 let diff:number = date2.getTime() - date1.getTime(); //如果为负数,。则转为正数 if(diff<0){ diff = -diff; } //计算出相差小时 let hours:number = Math.floor(diff / 3600000); return hours; } console.log('相差时间:'+compareTime(time[0],time[1])); console.log('相差时间:'+compareTime(time[1],time[2]));
作用:计算小时差
说明:JavaScript不能直接用,改改语法或者...将TS编译成JS就可以