| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- // utils/day.js
- import dayjs from 'dayjs'
- import customParseFormat from 'dayjs/plugin/customParseFormat'
- import 'dayjs/locale/en' // 英文月份缩写依赖英文 locale
- dayjs.extend(customParseFormat)
- dayjs.locale('en')
- // 解析并返回 dayjs 实例
- const parse = str =>
- dayjs(str, 'MMM D, YYYY, h:mm:ss A')
- // 1️⃣ 2025年7月4日
- export const toChineseDate = str =>
- parse(str).format('YYYY年M月D日')
- export const toChineseDateMonth = str =>
- parse(str).format('M月D日')
- // 2️⃣ 上午 / 下午 / 晚上
- export const getDayPeriod = str => {
- const d = parse(str)
- const hm = d.hour() * 60 + d.minute()
- if (hm >= 360 && hm < 720) return '上午'
- if (hm >= 780 && hm < 960) return '下午'
- if (hm >= 1110 && hm < 1260) return '晚上'
- return ''
- }
- /**
- * 通用日期格式化函数
- * @param {string} dateStr - 日期字符串
- * @param {string} format - 目标格式
- * @returns {string} 格式化后的日期
- */
- export const formatDate = (dateStr, format) => {
- if (!dateStr) return ''
- try {
- let dayjsInstance
- // 尝试解析不同的日期格式
- if (typeof dateStr === 'string') {
- // 处理 "Aug 11, 2025, 6:00:00 AM" 格式
- if (dateStr.includes(',') && (dateStr.includes('AM') || dateStr.includes('PM'))) {
- dayjsInstance = dayjs(dateStr, 'MMM D, YYYY, h:mm:ss A')
- }
- // 处理 "2025-08-11 06:00:00" 格式
- else if (dateStr.includes('-') && dateStr.includes(':')) {
- dayjsInstance = dayjs(dateStr, 'YYYY-MM-DD HH:mm:ss')
- }
- // 其他格式尝试自动解析
- else {
- dayjsInstance = dayjs(dateStr)
- }
- } else {
- dayjsInstance = dayjs(dateStr)
- }
- // 检查解析是否成功
- if (!dayjsInstance.isValid()) {
- console.warn('日期解析失败:', dateStr)
- return dateStr
- }
- // 根据目标格式进行格式化
- let result
- if (format === 'yyyy-MM-dd HH:mm:ss') {
- result = dayjsInstance.format('YYYY-MM-DD HH:mm:ss')
- } else if (format === 'yyyy-MM-dd') {
- result = dayjsInstance.format('YYYY-MM-DD')
- } else if (format === 'HH:mm:ss') {
- result = dayjsInstance.format('HH:mm:ss')
- } else if (format === 'HH:mm') {
- result = dayjsInstance.format('HH:mm')
- } else if (format === 'MM/DD') {
- result = dayjsInstance.format('MM/DD')
- } else {
- // 默认转换为中文日期格式
- result = dayjsInstance.format('YYYY年M月D日')
- }
- return result
- } catch (error) {
- console.error('日期格式化失败:', error, dateStr)
- return dateStr
- }
- }
|