83 lines
2.3 KiB
JavaScript
83 lines
2.3 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;
|
||
}
|
||
|
||
//计算当前日期占全年的进度数据
|
||
// 示例用法
|
||
// 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);
|
||
}
|
||
|
||
|
||
|
||
export {
|
||
formatDate,
|
||
getDateAfterDays,
|
||
getDaysDifference,
|
||
getYearProgress
|
||
} |