1.首先需要获取时间
在时间这一块,我经常会犯错,对于时间格式为YYYY-MM-DD 是无法进行相减的,所以我们在获取时间的时候,千外不要多此一举进行格式化
getTime()是获取毫秒数
var a=new Date(date1).getTime();
var b=new Date(date2).getTime();
注意事项:
new Date() ; //参数可以为整数; 也可以为字符串; 但格式必须正确
new Date(2020,1,1); //正确
new Date("2020/1/1"); //正确
new Date("2020-1-1"); //错误
2.相减
let diff=Math.floor((time2-time1)/360000);
3.根据你想获得差的单位进行换算
在这里我获取的是相差的小时
24*60*60*1000;
//天*时*分*毫秒
Math。floor()//对数进行下舍入。 4.9——4,-5.9——-6
注意事项:关于Math的对象方法:
官方:https://www.w3school.com.cn/jsref/jsref_obj_math.asp