317 lines
8.5 KiB
Plaintext

/*
* @Author: wangzhongjie
* @Date: 2024-02-21 17:12:56
* @LastEditors: wangzhongjie
* @LastEditTime: 2024-02-21 21:29:49
* @Description: 时间工具
* @Email: shutdown0630@163.com
*/
interface DateData {
getFullYear: () => number;
getMonth: () => number;
getDate: () => number;
getHours: () => number;
getMinutes: () => number;
getSeconds: () => number;
getDay: () => number;
getMilliseconds: () => number;
}
// 时间处理相关函数集合dayTs("2024-02-21 17:13:00").format("YYYY-MM-DD HH:mm:ss")
class DayTs {
dateData: Date
constructor(date: number | string | Date, offset?: number) {
this.dateData = new Date(date)
if (offset) {
this.dateData = new Date(Number(this.dateData) + offset)
}
}
private static _paddingZero(num: number, length: number = 2): string {
return `${num}`.padStart(length, '0');
}
// 格式化时间
public format(formatter: string = 'yyyy/MM/dd HH:mm:ss') {
const day = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
const obj: Record<string, string | number | ((dateData: DateData) => string | number)> = {
'Y{4}': (dateData: DateData) => dateData.getFullYear(),
'y+': (dateData: DateData) => dateData.getFullYear(),
'M{2}': (dateData: DateData) => DayTs._paddingZero(dateData.getMonth() + 1),
'D{2}': (dateData: DateData) => DayTs._paddingZero(dateData.getDate()),
'd{2}': (dateData: DateData) => DayTs._paddingZero(dateData.getDate()),
'H{2}': (dateData: DateData) => DayTs._paddingZero(dateData.getHours()),
'h{2}': (dateData: DateData) => DayTs._paddingZero(dateData.getHours() % 12),
'm{2}': (dateData: DateData) => DayTs._paddingZero(dateData.getMinutes()),
's{2}': (dateData: DateData) => DayTs._paddingZero(dateData.getSeconds()),
'S{3}': (dateData: DateData) => DayTs._paddingZero(dateData.getMilliseconds(), 3), // 添加毫秒支持
'M': (dateData: DateData) => dateData.getMonth() + 1,
'd': (dateData: DateData) => dateData.getDate(),
'H': (dateData: DateData) => dateData.getHours(),
'h': (dateData: DateData) => dateData.getHours() % 12,
'm': (dateData: DateData) => dateData.getMinutes(),
's': (dateData: DateData) => dateData.getSeconds(),
'CW': (dateData: DateData) => day[dateData.getDay()],
'W': (dateData: DateData) => dateData.getDay(),
};
const objEntries = Object.entries(obj);
for (let i = 0; i < objEntries.length; i++) {
const key = objEntries[i][0];
const value = objEntries[i][1];
const regexp = new RegExp(`(${key})([^a-zA-Z])?`);
const match = regexp.exec(formatter);
if (match) {
formatter = formatter.replace(match[1], `${(value as Function)(this.dateData)}`);
}
}
return formatter;
}
// 获取时间戳
valueOf() {
return this.dateData.getTime()
}
// 获取年份
year() {
//
return this.dateData.getFullYear()
}
// 获取月份
month() {
return this.dateData.getMonth() + 1
}
// 获取日期
date() {
return this.dateData.getDate()
}
// 获取小时
hour() {
return this.dateData.getHours()
}
// 获取分钟
minute() {
return this.dateData.getMinutes()
}
// 获取秒
second() {
return this.dateData.getSeconds()
}
// 获取毫秒
millisecond() {
return this.dateData.getMilliseconds()
}
// 获取星期几
day() {
return this.dateData.getDay()
}
// 获取一年中的第几天
dayOfYear() {
return 21
}
// 获取一月中的第几天
dayOfMonth() {
return 21
}
// 获取一周中的第几天
dayOfWeek(format?: boolean) {
const weeks = ["日", "一", "二", "三", "四", "五", "六",]
return format ? weeks[this.dateData.getDay()] : this.dateData.getDay() + ""
}
// 获取两个时间差值
diff(date: Date | string, unit?: Unit, isFloat?: boolean) {
// 计算this.dateData和date的时间差
const date1 = new Date(this.dateData)
const date2 = new Date(date)
// 计算时间差
const diffValue = date1.getTime() - date2.getTime()
if (unit) {
if (unit === "ms" || unit === "millisecond") {
return diffValue
}
if (unit === "s" || unit === "second") {
return Math.floor(diffValue / 1000)
}
if (unit === "m" || unit === "minute") {
return Math.floor(diffValue / 1000 / 60)
}
if (unit === "h" || unit === "hour") {
return Math.floor(diffValue / 1000 / 60 / 60)
}
if (unit === "d" || unit === "day") {
return Math.floor(diffValue / 1000 / 60 / 60 / 24)
}
if (unit === "w" || unit === "week") {
return Math.floor(diffValue / 1000 / 60 / 60 / 24 / 7)
}
if (unit === "M" || unit === "month") {
return Math.floor(diffValue / 1000 / 60 / 60 / 24 / 30)
}
if (unit === "Q" || unit === "quarter") {
return Math.floor(diffValue / 1000 / 60 / 60 / 24 / 30 / 3)
}
if (unit === "y" || unit === "year") {
return Math.floor(diffValue / 1000 / 60 / 60 / 24 / 365)
}
}
return diffValue
}
// 获取两个时间差值-传入时间戳
diffByDateTime(startTime: number, endTime: number, unit?: Unit) {
// 计算时间差
const diffValue = endTime - startTime
if (unit) {
if (unit === "ms" || unit === "millisecond") {
return diffValue
}
if (unit === "s" || unit === "second") {
return Math.floor(diffValue / 1000)
}
if (unit === "m" || unit === "minute") {
return Math.floor(diffValue / 1000 / 60)
}
if (unit === "h" || unit === "hour") {
return Math.floor(diffValue / 1000 / 60 / 60)
}
if (unit === "d" || unit === "day") {
return Math.floor(diffValue / 1000 / 60 / 60 / 24)
}
if (unit === "w" || unit === "week") {
return Math.floor(diffValue / 1000 / 60 / 60 / 24 / 7)
}
if (unit === "M" || unit === "month") {
return Math.floor(diffValue / 1000 / 60 / 60 / 24 / 30)
}
if (unit === "Q" || unit === "quarter") {
return Math.floor(diffValue / 1000 / 60 / 60 / 24 / 30 / 3)
}
if (unit === "y" || unit === "year") {
return Math.floor(diffValue / 1000 / 60 / 60 / 24 / 365)
}
}
return diffValue
}
// 增加时间
add(value: number, unit: Unit) {
let newDate: number = 0
// 从秒开始
if (unit === "s" || unit === "second") {
newDate = this.dateData.setSeconds(this.dateData.getSeconds() + value)
}
// 从分开始
if (unit === "m" || unit === "minute") {
newDate = this.dateData.setMinutes(this.dateData.getMinutes() + value)
}
// 从小时开始
if (unit === "h" || unit === "hour") {
newDate = this.dateData.setHours(this.dateData.getHours() + value)
}
// 从天开始
if (unit === "d" || unit === "day") {
newDate = this.dateData.setDate(this.dateData.getDate() + value)
}
return new DayTs(newDate)
}
// 减少时间
subtract(value: number, unit: Unit) {
console.log(value.toString(), unit)
return 123456
}
// 时间开始
startOf(unit: StartEndUnit) {
console.log(unit)
return 123456
}
// 时间结束
endOf(unit: StartEndUnit) {
console.log(unit)
return 123456
}
// 是否同一天
compare(date: Date | number | string) {
let tmp = dayTs(date)
let isDay = this.year() === tmp.year() && this.month() === tmp.month() && this.date() === tmp.date()
return isDay
}
/**
* 秒转标准时间格式
* @param time 时间长度 单位秒
* @param showHour
* @returns
*/
len2time(time: string | number, showHour: boolean = false) {
let duration = +Number(time)
let hour = Math.floor(duration / (60 * 60))
let min = Math.floor((duration % (60 * 60)) / 60)
let seconds = Math.floor(duration % 60)
let timestamp = ""
if (hour > 0 || showHour) {
timestamp += hexTime(hour) + ":"
}
return timestamp + hexTime(min) + ":" + hexTime(seconds)
}
}
const hexTime = (num: number) => {
return num < 10 ? `0${num}` : num + ''
}
type BaseUnit =
"day" |
"d" |
"month" |
"M" |
"quarter" |
"Q" |
"year" |
"y" |
"week" |
"w" |
"hour" |
"h" |
"minute" |
"m" |
"second" |
"s";
type Unit = BaseUnit | "millisecond" | "ms";
type StartEndUnit = BaseUnit | "isoWeek" | "date" | "D";
// const proto = DayTs.prototype
const dayTs = (date?: number | string | Date, offset?: number) => {
if (!date) {
date = new Date()
}
return new DayTs(date, offset)
}
// dayTs.prototype = proto;
export default dayTs