Skip to content
大纲

获取两个日期之间的差值

语法

js
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) : 设置差值的单位,支持以下值。
dayhourminutesecondms
小时分钟毫秒

返回值

Number : 两个日期之间的差值。

源码

js
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]);
};

例子

js
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); //=> 1
console.log(result2); //=> 24
console.log(result3); //=> 1440
console.log(result4); //=> 86400
console.log(result5); //=> 86400000

添加版本

1.2.0

Released under the MIT License.