天数计算器 - 日期、时间计算器

655 阅读1分钟

如果需要在日期工具类中增加返回相差多少周、多少天、多少月、多少年的计算功能,可以添加一个静态方法来实现。下面是一个示例。

static getDateDiff(date1, date2) {
  const timeDiff = Math.abs(date2.getTime() - date1.getTime());
  const diffYears = Math.floor(timeDiff / (1000 * 60 * 60 * 24 * 365));
  const diffMonths = Math.floor(timeDiff / (1000 * 60 * 60 * 24 * 30));
  const diffWeeks = Math.floor(timeDiff / (1000 * 60 * 60 * 24 * 7));
  const diffDays = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
  return {
    years: diffYears,
    months: diffMonths,
    weeks: diffWeeks,
    days: diffDays
  };
}

上述代码中,getDateDiff() 方法接受两个参数,分别表示要计算相差时间的日期对象。该方法会返回一个包含相差年份、月份、周数和天数的对象,具体计算方式如下:

  • 相差年份:将两个日期对象之间的毫秒数除以一年的毫秒数(约为 1000 * 60 * 60 * 24 * 365) 并向下取整;
  • 相差月份:将两个日期对象之间的毫秒数除以一月的毫秒数(约为 1000 * 60 * 60 * 24 * 30) 并向下取整;
  • 相差周数:将两个日期对象之间的毫秒数除以一周的毫秒数(约为 1000 * 60 * 60 * 24 * 7) 并向下取整;
  • 相差天数:将两个日期对象之间的毫秒数除以一天的毫秒数(即 1000 * 60 * 60 * 24) 并向下取整。

预览:

源码下载:ext.dcloud.net.cn/plugin?id=1…