lrj
16 小时以前 ae3349d2ff53767b5bc9cb30e1bf7e15f9e814ee
wx/lib/utils.js
@@ -7,18 +7,41 @@
 * @returns {string} 格式化后的日期字符串
 */
function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!date) return ''
  const d = new Date(date)
  if (date === null || date === undefined || date === '') return ''
  let d
  // 数字:可能是时间戳(秒/毫秒)
  if (typeof date === 'number') {
    // 小于 1e12 视为秒,转换为毫秒
    d = new Date(date < 1e12 ? date * 1000 : date)
  } else if (typeof date === 'string') {
    let s = date.trim()
    if (!s) return ''
    // 处理 ISO 和常见后端格式
    // 1) 含 'T' 的 ISO 字符串,去掉毫秒与 Z 的影响(保持本地时间)
    s = s.replace('T', ' ').replace(/\.000Z?$/i, '')
    // 2) YYYY-MM-DD -> 微信 JSCore 对连字符解析不稳定,转斜杠
    if (/^\d{4}-\d{2}-\d{2}(?:\s+\d{2}:\d{2}:\d{2})?$/.test(s)) {
      s = s.replace(/-/g, '/')
      // 仅日期补时间,避免 NaN
      if (s.length === 10) s += ' 00:00:00'
    }
    d = new Date(s)
  } else if (date instanceof Date) {
    d = date
  } else {
    return ''
  }
  if (isNaN(d.getTime())) return ''
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return format
    .replace('YYYY', year)
    .replace('MM', month)