118 lines
2.5 KiB
JavaScript
118 lines
2.5 KiB
JavaScript
/**
|
|
* 日期工具函数
|
|
*/
|
|
|
|
/**
|
|
* 格式化日期
|
|
* @param {Date} date - 日期对象
|
|
* @param {String} format - 格式字符串,默认 'YYYY-MM-DD'
|
|
* @returns {String} 格式化后的日期字符串
|
|
*/
|
|
function formatDate(date, format = 'YYYY-MM-DD') {
|
|
if (!date) return ''
|
|
|
|
const d = new Date(date)
|
|
const year = d.getFullYear()
|
|
const month = String(d.getMonth() + 1).padStart(2, '0')
|
|
const day = String(d.getDate()).padStart(2, '0')
|
|
const hour = String(d.getHours()).padStart(2, '0')
|
|
const minute = String(d.getMinutes()).padStart(2, '0')
|
|
const second = String(d.getSeconds()).padStart(2, '0')
|
|
|
|
return format
|
|
.replace('YYYY', year)
|
|
.replace('MM', month)
|
|
.replace('DD', day)
|
|
.replace('HH', hour)
|
|
.replace('mm', minute)
|
|
.replace('ss', second)
|
|
}
|
|
|
|
/**
|
|
* 计算距离今天还有多少天
|
|
* @param {Date} targetDate - 目标日期
|
|
* @returns {Number} 天数差
|
|
*/
|
|
function getDaysUntil(targetDate) {
|
|
const today = new Date()
|
|
today.setHours(0, 0, 0, 0)
|
|
|
|
const target = new Date(targetDate)
|
|
target.setHours(0, 0, 0, 0)
|
|
|
|
const diff = target.getTime() - today.getTime()
|
|
return Math.ceil(diff / (1000 * 60 * 60 * 24))
|
|
}
|
|
|
|
/**
|
|
* 判断是否是今天
|
|
*/
|
|
function isToday(date) {
|
|
return getDaysUntil(date) === 0
|
|
}
|
|
|
|
/**
|
|
* 判断是否已过期
|
|
*/
|
|
function isPast(date) {
|
|
return getDaysUntil(date) < 0
|
|
}
|
|
|
|
/**
|
|
* 判断是否即将到来
|
|
*/
|
|
function isUpcoming(date) {
|
|
const days = getDaysUntil(date)
|
|
return days > 0 && days <= 7
|
|
}
|
|
|
|
/**
|
|
* 获取星期几
|
|
*/
|
|
function getWeekDay(date) {
|
|
const weekdays = ['日', '一', '二', '三', '四', '五', '六']
|
|
const d = new Date(date)
|
|
return weekdays[d.getDay()]
|
|
}
|
|
|
|
/**
|
|
* 判断是否在本月
|
|
*/
|
|
function isInThisMonth(date) {
|
|
const today = new Date()
|
|
const target = new Date(date)
|
|
return today.getFullYear() === target.getFullYear() &&
|
|
today.getMonth() === target.getMonth()
|
|
}
|
|
|
|
/**
|
|
* 获取本月的开始日期和结束日期
|
|
*/
|
|
function getMonthRange(year, month) {
|
|
const start = new Date(year, month - 1, 1)
|
|
const end = new Date(year, month, 0)
|
|
return { start, end }
|
|
}
|
|
|
|
/**
|
|
* 获取日期对象(从YYYY-MM-DD字符串)
|
|
*/
|
|
function parseDate(dateString) {
|
|
if (!dateString) return null
|
|
const parts = dateString.split('-')
|
|
return new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]))
|
|
}
|
|
|
|
module.exports = {
|
|
formatDate,
|
|
getDaysUntil,
|
|
isToday,
|
|
isPast,
|
|
isUpcoming,
|
|
getWeekDay,
|
|
isInThisMonth,
|
|
getMonthRange,
|
|
parseDate
|
|
}
|
|
|