day.js這個日期庫真的是很不錯的日期庫,足夠滿足日常的開發需求。
Day.js中文網 (fenxianglu.cn)
需求:獲取兩個日期相差的時間,轉化為年月日的形式;話不多少,直接放代碼
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";dayjs.extend(duration);// 計算日期差異并返回格式化字符串
export function getDateDiff(startDateString, endDateString) {// 創建起始日期和結束日期對象const startDate = dayjs(startDateString, "YYYY-MM-DD"); const endDate = dayjs(endDateString, "YYYY-MM-DD");// 計算日期差異const diff = endDate.diff(startDate);// 提取差異的時間單位const duration = dayjs.duration(diff);const years = duration.years();const months = duration.months();const days = duration.days();// 格式化為字符串const formattedDiff = `${years}年${months}月${days}天`;return formattedDiff;
}
測試一下:
const start = '2022-01-01';const end = '2023-03-15';const diff = getDateDiff(start, end);console.log(diff); // 輸出:1年2月14日