Files
wxapp_escort/utils/date.js
T
2026-10-24 18:49:02 +08:00

64 lines
1.7 KiB
JavaScript

// 小程序各端对 new Date('YYYY-MM-DD') 的解析并不一致,纯日期统一按本地年月日构造。
function parseDate(value) {
if (value instanceof Date) {
return Number.isNaN(value.getTime()) ? null : value
}
if (!value) return null
const text = String(value)
const dateOnly = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text)
if (dateOnly) {
const year = Number(dateOnly[1])
const month = Number(dateOnly[2])
const day = Number(dateOnly[3])
const date = new Date(year, month - 1, day)
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
return null
}
return date
}
const date = new Date(text)
return Number.isNaN(date.getTime()) ? null : date
}
function pad(value) {
return String(value).padStart(2, '0')
}
function formatDate(value, fallback = '') {
const date = parseDate(value)
if (!date) return fallback
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}
function formatDateTime(value, fallback = '') {
const date = parseDate(value)
if (!date) return fallback
return `${formatDate(date)} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}
function calcAge(value) {
const birth = parseDate(value)
if (!birth) return 0
const today = new Date()
let age = today.getFullYear() - birth.getFullYear()
const monthDelta = today.getMonth() - birth.getMonth()
if (monthDelta < 0 || (monthDelta === 0 && today.getDate() < birth.getDate())) age--
return age > 0 && age <= 120 ? age : 0
}
function toISOString(value) {
const date = parseDate(value)
return date ? date.toISOString() : null
}
module.exports = {
parseDate,
formatDate,
formatDateTime,
calcAge,
toISOString
}