You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.7 KiB
JavaScript

/**
* 日期格式化工具函数
*/
/**
* 将日期对象格式化为 YYYY-MM-DD 格式的字符串
* @param {Date} date - 日期对象
* @returns {string} 格式化后的日期字符串
*/
export function formatDate(date) {
if (!date) return '';
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
/**
* 将日期对象格式化为 YYYY-MM-DD HH:mm:ss 格式的字符串
* @param {Date} date - 日期对象
* @returns {string} 格式化后的日期时间字符串
*/
export function formatDateTime(date) {
if (!date) return '';
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}`;
}
/**
* 根据时间范围文字(如"近1年")计算开始和结束日期
* @param {string} timeRange - 时间范围文字
* @returns {Object} 包含开始和结束日期的对象
*/
export function getDateRangeByTimeRange(timeRange) {
const endDate = new Date();
const startDate = new Date();
if (timeRange === '近1年') {
startDate.setFullYear(endDate.getFullYear() - 1);
} else if (timeRange === '近2年') {
startDate.setFullYear(endDate.getFullYear() - 2);
} else if (timeRange === '近3年') {
startDate.setFullYear(endDate.getFullYear() - 3);
}
return {
start_date: formatDate(startDate),
end_date: formatDate(endDate)
};
}