Files
Neo-ZQYY/tmp/DEMO-miniprogram/miniprogram/utils/time.wxs

87 lines
2.4 KiB
XML
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.
// WXS 时间格式化桥接 — WXML 中不能调用 TS/JS 模块,需通过 WXS 桥接
// 规范docs/miniprogram-dev/design-system/DATETIME-DISPLAY-STANDARD.md
//
// 规则:
// < 120s -> 刚刚
// 2~59min -> N分钟前
// 1~23h -> N小时前
// 1~3d -> N天前
// >3d 同年 -> MM-DD
// >3d 跨年 -> YYYY-MM-DD
function relativeTime(value) {
if (value === undefined || value === null || value === '') return '--'
var ts
if (typeof value === 'number') {
ts = value
} else {
var parsed = getDate(value)
ts = parsed.getTime()
if (isNaN(ts)) return '--'
}
var now = getDate().getTime()
var diff = Math.floor((now - ts) / 1000)
if (diff < 120) return ''
if (diff < 3600) return Math.floor(diff / 60) + ''
if (diff < 86400) return Math.floor(diff / 3600) + ''
if (diff < 259200) return Math.floor(diff / 86400) + ''
var date = getDate(ts)
var nowDate = getDate(now)
var year = date.getFullYear()
var nowYear = nowDate.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var mm = month < 10 ? '0' + month : '' + month
var dd = day < 10 ? '0' + day : '' + day
if (year === nowYear) return mm + '-' + dd
return year + '-' + mm + '-' + dd
}
// IM
// -> HH:mm
// 今年非今天 -> MM-DD HH:mm
// 跨年 -> YYYY-MM-DD HH:mm
function imTime(value) {
if (value === undefined || value === null || value === '') return ''
var ts
if (typeof value === 'number') {
ts = value
} else {
var parsed = getDate(value)
ts = parsed.getTime()
if (isNaN(ts)) return ''
}
var date = getDate(ts)
var now = getDate()
var hh = date.getHours()
var mn = date.getMinutes()
var hhStr = hh < 10 ? '0' + hh : '' + hh
var mnStr = mn < 10 ? '0' + mn : '' + mn
var timeStr = hhStr + ':' + mnStr
var isSameDay =
date.getFullYear() === now.getFullYear() &&
date.getMonth() === now.getMonth() &&
date.getDate() === now.getDate()
if (isSameDay) return timeStr
var month = date.getMonth() + 1
var day = date.getDate()
var mm = month < 10 ? '0' + month : '' + month
var dd = day < 10 ? '0' + day : '' + day
if (date.getFullYear() === now.getFullYear()) return mm + '-' + dd + ' ' + timeStr
return date.getFullYear() + '-' + mm + '-' + dd + ' ' + timeStr
}
module.exports = {
relativeTime: relativeTime,
imTime: imTime,
}