emis-frontend/src/utils/dateUtils.js
2025-07-29 15:17:13 +08:00

101 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import dayjs from "dayjs"; // 导入日期js
// 以下是时间计算类函数 ------------------------------------------------------时间计算---------------------------------------
/**
* 计算时差
* startDate:开始时间
* endDate:结束时间
* unit:单位 days、months、yesrs
*/
export function timeDiffTime(startDate, endDate, unit = "days") {
if(unit=="days"){
endDate=timeFormatDay(endDate);
startDate=timeFormatDay(startDate);
}
return dayjs(endDate).diff(startDate, unit);
}
/**
* 比较时间,是否之前
* startDate:开始时间
* endDate:结束时间
* unit:单位 days、months、yesrs
*/
export function timeIsBefore(startDate, endDate, unit = "days") {
return dayjs(startDate).isBefore(endDate, unit);
}
/**
* 时间加计算函数
* date:原时间
* num:需要增加的时间数量
* nuit:增加时间的单位 day year
*/
export function timeAdd(date, num = 1, nuit = "day", format = "YYYY-MM-DD") {
return dayjs(date)
.add(num, nuit)
.format(format);
}
/**
* 时间格式化函数
* date 需要格式化的数据
* format 格式化的格式
*/
export function timeFormat(date, format = "YYYY-MM-DD HH:mm:ss") {
return dayjs(date).format(format);
}
export function timeFormatDay(date, format = "YYYY-MM-DD") {
return dayjs(date).format(format);
}
/**
* 查询时间是周几
*/
export function timeInWeek(date) {
return dayjs(date).day();
}
/**
*处理excel 数字转时间
*/
export function excelDateToJSDate(excelDate) {
// Excel把1900年1月1日存储为数字1
const date = new Date(1900, 0, excelDate - 1);
// 时间格式化为 YYYY-MM-DD HH:mm:ss
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
/**
* 获取上个月的年月 格式 yyyy-mm
*/
export function getLastMonthYearMonth() {
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth();
// 计算上一个月的年月
let lastMonth, lastYear;
if (month === 0) {
// 如果是1月,上一个月是去年12月
lastMonth = 11;
lastYear = year - 1;
} else {
lastMonth = month - 1;
lastYear = year;
}
// 格式化为 YYYY-MM
return `${lastYear}-${String(lastMonth + 1).padStart(2, "0")}`;
}