dayjs实现两个日期相减并格式化

dayjs实现两个日期相减并格式化

徐徐
前端
发布于2024-08-24 16:14:01
🌺前言
dayjs实现两个日期相减并格式化

typescript

import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
dayjs.extend(duration);
/**
 *计算时间之差
 * @param oldTime
 * @param newTime
 * @returns
 */
export const timeDiff = (oldTime:string, newTime?:string) => {
  const  startTime = dayjs(oldTime)
  const endTime = newTime?dayjs(newTime):dayjs()
  // 计算日期差异
  const diff = endTime.diff(startTime);

  // 提取差异的时间单位
  const duration = dayjs.duration(diff);
  const years = duration.years();
  const months = duration.months();
  const days = duration.days();

  const hours = duration.hours()
  const minute  =duration.minutes()
  const second = duration.seconds()
  return {
    years,
    months,
    days,
    hours,
    minute,
    second
  }

};
文章最后更新于 2024-08-24 16:14:32
留言
暂无数据

~~空空如也