AI-accounting-soft-uniApp/utils/date.js
2025-12-12 16:49:06 +08:00

60 lines
1.8 KiB
JavaScript

// 日期工具函数
// 格式化日期
export 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)
}
// 格式化日期为中国格式 (例如: 2025年1月1日 13:40 星期三)
export function formatChineseDate(date) {
if (!date) return ''
const d = new Date(date)
const year = d.getFullYear()
const month = d.getMonth() + 1
const day = d.getDate()
const hour = String(d.getHours()).padStart(2, '0')
const minute = String(d.getMinutes()).padStart(2, '0')
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
const weekday = weekdays[d.getDay()]
return `${year}${month}${day}${hour}:${minute} ${weekday}`
}
// 获取周的开始日期
export function getWeekStart(date = new Date()) {
const d = new Date(date)
const day = d.getDay()
const diff = d.getDate() - day + (day === 0 ? -6 : 1) // 周一
return new Date(d.setDate(diff))
}
// 获取月的开始日期
export function getMonthStart(date = new Date()) {
const d = new Date(date)
return new Date(d.getFullYear(), d.getMonth(), 1)
}
// 获取月的结束日期
export function getMonthEnd(date = new Date()) {
const d = new Date(date)
return new Date(d.getFullYear(), d.getMonth() + 1, 0)
}