|
@@ -0,0 +1,74 @@
|
|
|
|
|
+// utils/format.js — 通用格式化工具(时间/金额)
|
|
|
|
|
+// 规范:后端金额以「分」为单位整数返回,前端除以 100 转「元」展示
|
|
|
|
|
+// 时间:后端返回 ISO 8601(2026-08-15T14:30:00),统一转为 yyyy-MM-dd HH:mm:ss
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 解析 ISO 8601 时间为本地 Date,兼容 iOS(不能用 new Date('yyyy-MM-dd HH:mm:ss'))
|
|
|
|
|
+ * @param {String} str ISO 时间串,如 '2026-08-15T14:30:00'
|
|
|
|
|
+ * @returns {Date|null}
|
|
|
|
|
+ */
|
|
|
|
|
+export function parseDate(str) {
|
|
|
|
|
+ if (!str) return null
|
|
|
|
|
+ if (typeof str !== 'string') return null
|
|
|
|
|
+ // 将 'yyyy-MM-dd HH:mm:ss' / 'yyyy-MM-ddTHH:mm:ss' 统一转成 iOS 可解析格式
|
|
|
|
|
+ var normalized = str.replace('T', ' ').trim()
|
|
|
|
|
+ // 去掉毫秒与时区后缀(若有)
|
|
|
|
|
+ normalized = normalized.replace(/\.\d+/, '')
|
|
|
|
|
+ normalized = normalized.replace(/Z$/, '')
|
|
|
|
|
+ // 纯日期补零时分秒
|
|
|
|
|
+ if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) {
|
|
|
|
|
+ normalized += ' 00:00:00'
|
|
|
|
|
+ }
|
|
|
|
|
+ var d = new Date(normalized.replace(/-/g, '/'))
|
|
|
|
|
+ if (isNaN(d.getTime())) {
|
|
|
|
|
+ d = new Date(normalized)
|
|
|
|
|
+ }
|
|
|
|
|
+ return isNaN(d.getTime()) ? null : d
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function pad(n) {
|
|
|
|
|
+ return n < 10 ? '0' + n : '' + n
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 格式化时间为 yyyy-MM-dd HH:mm:ss
|
|
|
|
|
+ * @param {String|Date|Number} v ISO 串 / Date / 时间戳
|
|
|
|
|
+ */
|
|
|
|
|
+export function formatDateTime(v) {
|
|
|
|
|
+ var d = v instanceof Date ? v : (typeof v === 'number' ? new Date(v) : parseDate(v))
|
|
|
|
|
+ if (!d) return ''
|
|
|
|
|
+ return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
|
|
|
|
|
+ ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds())
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 格式化时间为 yyyy-MM-dd(仅日期)
|
|
|
|
|
+ */
|
|
|
|
|
+export function formatDate(v) {
|
|
|
|
|
+ var d = v instanceof Date ? v : (typeof v === 'number' ? new Date(v) : parseDate(v))
|
|
|
|
|
+ if (!d) return ''
|
|
|
|
|
+ return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate())
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 分 → 元(保留两位小数)
|
|
|
|
|
+ * @param {Number} fen 以「分」为单位的整数金额
|
|
|
|
|
+ * @returns {String} 如 '199.00'
|
|
|
|
|
+ */
|
|
|
|
|
+export function fenToYuan(fen) {
|
|
|
|
|
+ if (fen === null || fen === undefined || fen === '') return '0.00'
|
|
|
|
|
+ var n = Number(fen)
|
|
|
|
|
+ if (isNaN(n)) return '0.00'
|
|
|
|
|
+ return (n / 100).toFixed(2)
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 元 → 分(整数,供下单等场景)
|
|
|
|
|
+ * @param {Number} yuan
|
|
|
|
|
+ * @returns {Number}
|
|
|
|
|
+ */
|
|
|
|
|
+export function yuanToFen(yuan) {
|
|
|
|
|
+ var n = Number(yuan)
|
|
|
|
|
+ if (isNaN(n)) return 0
|
|
|
|
|
+ return Math.round(n * 100)
|
|
|
|
|
+}
|