dayjs-time-utils
Version:
🚀 基于day.js的超级时间处理工具包 | 提供格式化、计算、节假日判断等全方位时间操作能力
130 lines (109 loc) • 3.8 kB
JavaScript
/**
* 基于day.js的时间处理工具包
* 功能包含:时间格式化、时间计算、时间比较、节假日判断等
* 依赖:day.js (需先安装)
*/
import dayjs from 'dayjs'
/**
* 时间工具类
*/
class TimeUtils {
/**
* 格式化时间为指定格式
* @param {Date|string} time - 时间对象或字符串
* @param {string} format - 格式字符串,默认'YYYY-MM-DD HH:mm:ss'
* @returns {string} 格式化后的时间字符串
*/
static format(time, format = 'YYYY-MM-DD HH:mm:ss') {
return dayjs(time).format(format)
}
/**
* 获取当前时间
* @param {string} format - 可选格式字符串
* @returns {string|dayjs.Dayjs} 格式化后的时间字符串或dayjs对象
*/
static now(format) {
return format ? dayjs().format(format) : dayjs()
}
/**
* 时间加减计算
* @param {Date|string} time - 基准时间
* @param {number} value - 增减值
* @param {string} unit - 单位('day','month','year','hour'等)
* @param {string} format - 可选格式字符串
* @returns {string|dayjs.Dayjs} 计算后的时间
*/
static add(time, value, unit, format) {
const result = dayjs(time).add(value, unit)
return format ? result.format(format) : result
}
/**
* 计算两个时间的差值
* @param {Date|string} start - 开始时间
* @param {Date|string} end - 结束时间
* @param {string} unit - 单位('day','month','year','hour'等)
* @returns {number} 差值
*/
static diff(start, end, unit) {
return dayjs(end).diff(dayjs(start), unit)
}
/**
* 判断是否为闰年
* @param {Date|string} time - 时间
* @returns {boolean} 是否为闰年
*/
static isLeapYear(time) {
return dayjs(time).isLeapYear()
}
/**
* 获取月份天数
* @param {Date|string} time - 时间
* @returns {number} 当月天数
*/
static daysInMonth(time) {
return dayjs(time).daysInMonth()
}
/**
* 判断是否为工作日(周一到周五)
* @param {Date|string} time - 时间
* @returns {boolean} 是否为工作日
*/
static isWeekday(time) {
const day = dayjs(time).day()
return day > 0 && day < 6
}
/**
* 获取相对时间描述(如"3天前")
* @param {Date|string} time - 时间
* @returns {string} 相对时间描述
*/
static fromNow(time) {
return dayjs(time).fromNow()
}
/**
* 判断是否为中国的法定节假日
* @param {Date|string} time - 时间
* @returns {boolean} 是否为节假日
*/
static isHolidayCN(time) {
const date = dayjs(time)
const month = date.month() + 1
const day = date.date()
// 元旦(1月1日)
if (month === 1 && day === 1) return true
// 春节(农历正月初一,这里简化为公历1月25日左右)
if (month === 1 && day >= 25 && day <= 31) return true
// 清明节(4月4日或5日)
if (month === 4 && (day === 4 || day === 5)) return true
// 劳动节(5月1日)
if (month === 5 && day === 1) return true
// 端午节(农历五月初五,简化为6月25日左右)
if (month === 6 && day >= 25 && day <= 30) return true
// 中秋节(农历八月十五,简化为9月15日左右)
if (month === 9 && day >= 15 && day <= 20) return true
// 国庆节(10月1日-7日)
if (month === 10 && day >= 1 && day <= 7) return true
return false
}
}
export default TimeUtils