Files
workspace/code/base-project/base-uniapp-main/src/utils/time.ts
T
2025-10-09 17:32:01 +08:00

75 lines
2.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import dayjs from 'dayjs'
// 定义单位的类型
type Unit = 'day' | 'week' | 'month' | 'year'
/**
* 获取指定日期之前的日期
* @param value 数字,表示要减去的时间量
* @param unit 时间单位,可以是 'day'、'week'、'month' 或 'year'
* @returns 返回计算后的日期
*/
export function getDateBefore(value: number, unit: Unit): string {
return dayjs().subtract(value, unit).format('YYYY-MM-DD')
}
export function getTimeDifference(dateStr1: string, dateStr2: string) {
const date1 = new Date(dateStr1)
if (!dateStr2) {
return Number.NaN
}
const date2 = new Date(dateStr2)
const differenceInMilliseconds = date2.getTime() - date1.getTime()
return differenceInMilliseconds
}
// 获取当前年份
export function getYear(): string {
return dayjs().year().toString()
}
export function getMonth(): string {
// 获取当前月份并加1,确保是1-12范围
const month = (dayjs().month() + 1).toString()
return month.padStart(2, '0') // 如果是单数月,前面加0
}
export function getDay(): string {
// 获取当前日期并转换为字符串
const day = dayjs().date().toString()
return day.padStart(2, '0') // 如果是单数天,前面加0
}
export function getCurrentDate() {
return dayjs().format('YYYY-MM-DD')
}
export function getCurrentDateTimeWithSeconds() {
return dayjs().format('YYYY-MM-DD HH:mm:ss')
}
export function stringToTimestamp(timeString: string, format: string): number {
const parsedDate = dayjs(timeString, format)
if (!parsedDate.isValid()) {
throw new Error('Invalid date string or format')
}
return parsedDate.valueOf() // 返回时间戳(以毫秒为单位)
}
export function timestampToString(timestamp: number, format: string): string {
const parsedDate = dayjs(timestamp)
return parsedDate.format(format)
}
/**
* 判断传入日期是否在今天的60天以内(含60天)
* @param dateStr - 日期字符串(如 '2025-02-01')
* @returns boolean - true 表示在60天内(包括第60天),false 表示超过60天
*/
export function isWithin60Days(dateStr: string): boolean {
if (!dateStr.trim()) {
return true
}
const inputDate = dayjs(dateStr)
const today = dayjs()
const diffDays = today.diff(inputDate, 'day')
return diffDays >= 0 && diffDays <= 60
}