123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- // 时间戳转换为年月日时分秒
- export const timesTampChange = (timestamp, format = 'Y-M-D h:m:s') => {
- if (!timestamp) return ''
- const date = new Date(timestamp)
- const Y = date.getFullYear().toString()
- const M = (date.getMonth() + 1).toString().padStart(2, '0')
- const D = date.getDate().toString().padStart(2, '0')
- const h = date.getHours().toString().padStart(2, '0')
- const m = date.getMinutes().toString().padStart(2, '0')
- const s = date.getSeconds().toString().padStart(2, '0')
- const formatter = { 'Y': Y, 'M': M, 'D': D, 'h': h, 'm': m, 's': s } // 替换format中的占位符
- let formattedDate = format.replace(/Y|M|D|h|m|s/g, matched => formatter[matched]) // 使用正则表达式匹配并替换占位符
-
- if (!formattedDate) formattedDate = Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
- return formattedDate
- }
- // 根据生日时间戳计算年龄
- export const getAgeByBirthdayTimestamp = (timestamp) => {
- const now = new Date()
- const birthday = new Date(timestamp)
- const age = now.getFullYear() - birthday.getFullYear()
- return age
- }
- // 将YYYY-MM转换为时间戳
- export const convertYearMonthToTimestamp = (yearMonth) => {
- const regex = /^\d{4}-\d{2}$/
- if (!regex.test(yearMonth)) {
- throw new Error("Invalid input format. Expected 'YYYY-MM'.")
- }
- const [year, month] = yearMonth.split('-').map(Number)
- const date = new Date(Date.UTC(year, month - 1, 1))
- const timestamp = date.getTime()
- return timestamp
- }
- export const getNextDate = (createTimestamp, format = 'YYYY-MM-DD', type, startTime) => {
- if (type === 'day') createTimestamp = createTimestamp * 24 * 60 * 60 * 1000
- if (type === 'hour') createTimestamp = createTimestamp * 60 * 60 * 1000
- let date = new Date(startTime ? startTime + createTimestamp : new Date().getTime() + createTimestamp)
- let year = date.getFullYear()
- let month = date.getMonth() + 1
- let day = date.getDate()
- month = month < 10 ? `0${month}` : month
- day = day < 10 ? `0${day}` : day
- if (format === 'YYYY-MM') {
- return `${year}-${month}`
- } else if (format === 'YYYY-MM-DD') {
- return `${year}-${month}-${day}`
- } else {
- return `${year}-${month}-${day}` // 默认返回 yyyy-mm-dd
- }
- }
|