cxc-szcx-uniapp/utils/dateTime.js

59 lines
1.7 KiB
JavaScript

// 日期格式化函数 by liaody 2025-3-5
// 使用示例
///const now = new Date();
//const formattedDate = formatDate(now);
//console.log(formattedDate);
function formatDate(date, format = 'YYYY-MM-DD') {
if (!(date instanceof Date)) {
date = new Date(date);
}
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hour = String(date.getHours()).padStart(2, '0');
const minute = String(date.getMinutes()).padStart(2, '0');
const second = String(date.getSeconds()).padStart(2, '0');
return format
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hour)
.replace('mm', minute)
.replace('ss', second);
}
// 计算两个日期之间相差的天数
// 使用示例
// const dateA = '2025-01-01';
// const dateB = '2025-01-10';
// const daysDiff = getDaysDifference(dateA, dateB);
// console.log(daysDiff);
function getDaysDifference(date1, date2) {
const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
const firstDate = new Date(date1);
const secondDate = new Date(date2);
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
return diffDays;
}
// 使用示例
// const startDate = '2025-03-01';
// const daysToAdd = 5;
// const futureDate = getDateAfterDays(startDate, daysToAdd);
// const formattedFutureDate = formatDate(futureDate);
// console.log(formattedFutureDate);
// 获取指定日期之后 n 天的日期
function getDateAfterDays(date, days) {
const newDate = new Date(date);
newDate.setDate(newDate.getDate() + days);
return newDate;
}
export {
formatDate,
getDateAfterDays,
getDaysDifference
}