获取两个日期之间的差值
语法
import { getDayDiff } from 'warbler-js'const result = getDayDiff(date1, date2, unit)
参数
date1(String) : 指定日期1,可传参数同new Date(),并且支持yyyy-mm-dd格式。date2(String) : 指定日期2,可传参数同new Date(),并且支持yyyy-mm-dd格式。unit(String) : 设置差值的单位,支持以下值。
| day | hour | minute | second | ms |
|---|---|---|---|---|
| 天 | 小时 | 分钟 | 秒 | 毫秒 |
返回值
Number : 两个日期之间的差值。
源码
const getDayDiff = (date1, date2, unit) => {const myDate1 = typeof date1 === 'string' && date1.includes('-') ? date1.replace(/-/g, '/') : date1;const myDate2 = typeof date2 === 'string' && date2.includes('-') ? date2.replace(/-/g, '/') : date2;const map = {day: 1000 * 60 * 60 * 24,hour: 1000 * 60 * 60,minute: 1000 * 60,second: 1000,ms: 1,};return Math.abs((new Date(myDate2) - new Date(myDate1)) / (map[unit]));};
例子
import { getDayDiff } from 'warbler-js'// 以天为单位const result1 = getDayDiff("2021,9,15",'2021,9,16','day')// 以小时为单位const result2 = getDayDiff("2021,9,15",'2021,9,16','hour')// 以分钟为单位const result3 = getDayDiff("2021,9,15",'2021,9,16','minute')// 以秒为单位const result4 = getDayDiff("2021,9,15",'2021,9,16','second')// 以毫秒为单位const result5 = getDayDiff("2021,9,15",'2021,9,16','ms')console.log(result1) //=> 1console.log(result2) //=> 24console.log(result3) //=> 1440console.log(result4) //=> 86400console.log(result5) //=> 86400000
