cxc-szcx-uniapp/utils/dateTime.js

118 lines
3.3 KiB
JavaScript
Raw Normal View History

2025-03-06 18:35:00 +00:00
// 日期格式化函数 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;
}
function getDateAfterMonths(date, months) {
const newDate = new Date(date);
const originalDate = date.getDate();
// 保存原始年月日
const originalYear = date.getFullYear();
const originalMonth = date.getMonth();
// 计算目标年月
const totalMonths = originalMonth + months;
const expectedYear = originalYear + Math.floor(totalMonths / 12);
const expectedMonth = totalMonths % 12;
// 尝试设置新月份
newDate.setMonth(totalMonths);
// 处理月末边界情况
if (
newDate.getFullYear() !== expectedYear ||
newDate.getMonth() !== expectedMonth
) {
// 当设置月份失败时如1月31日设置到2月
// 设置为目标月份的最后一天
newDate.setFullYear(expectedYear, expectedMonth + 1, 0);
} else if (newDate.getDate() !== originalDate) {
// 当日期自动变化时如1月30日设置到2月
// 同样设置为目标月份的最后一天
newDate.setDate(0);
}
return newDate;
}
//计算当前日期占全年的进度数据
// 示例用法
// console.log(getYearProgress()); // 输出如 "35.42%"
function getYearProgress() {
const now = new Date(); // 当前时间
const year = now.getFullYear();
// 关键时间点
const yearStart = new Date(year, 0, 1); // 当年1月1日
const nextYearStart = new Date(year + 1, 0, 1); // 下一年1月1日
// 计算时间差(毫秒)
const totalMs = nextYearStart - yearStart; // 全年总时长
const passedMs = now - yearStart; // 已过时长
// 计算百分比保留2位小数
const progress = ((passedMs / totalMs) * 100).toFixed(2);
return parseFloat(progress);
}
2025-03-06 18:35:00 +00:00
export {
formatDate,
getDateAfterDays,
getDaysDifference,
getDateAfterMonths,
getYearProgress
2025-03-06 18:35:00 +00:00
}