微信小程式中將時間戳轉換為聊天格式

Mr_Tony發表於2020-10-31

該程式碼是對第三方庫內容進行轉換以方便使用wxs,也可以作為js使用:
https://www.npmjs.com/package/chat-date-format
使用方式:

呼叫:
chatDateFormat(timestamp, isDetail)

引數說明:
timestamp - 傳入時間戳
isDetail - 是否要顯示詳細時間

let chatDateFormat = require('chat-date-format')

    methods: {
      ...chatDateFormat
    }

    created () {
      this.chatDateFormat(new Date()) // 當前格式化時間 - 某天 xx:xx
      this.chatDateFormat(new Date(), true) // 出當前格式化詳細時間 - 某天 上午 xx:xx
    }

程式碼如下:

  /**
   * 格式化為IM所需顯示時間
   * @param {Date} timestamp 處理型別
   * @param {Boolean} isDetail 是否顯示詳細時間
   */
  function chatDateFormat (timestamp, isDetail = true) {
    var chatTime = { _date: timestamp || Date.now() }
    chatTime.init = function () {
      var time = getDate(chatTime._date).getTime()
      var now = getDate();
      chatTime._timeStamp = time
      chatTime._now = now.getTime()
      chatTime._nowYear = now.getFullYear()
      chatTime._nowMonth = now.getMonth() + 1
      chatTime._nowDay = now.getDate()
      chatTime._nowHour = now.getHours()
      chatTime._nowMinute = now.getMinutes()
      chatTime._nowSecond = now.getSeconds()
      chatTime._nowWeek = now.getDay()
      chatTime._argYear = getDate(chatTime._date).getFullYear()
      chatTime._argMonth = getDate(chatTime._date).getMonth() + 1
      chatTime._argDay = getDate(chatTime._date).getDate()
      chatTime._argHour = getDate(chatTime._date).getHours()
      chatTime._argMinute = getDate(chatTime._date).getMinutes()
      chatTime._argSecond = getDate(chatTime._date).getSeconds()
      chatTime._argWeek = getDate(chatTime._date).getDay()
    }
    chatTime.week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    chatTime.formatNumber = function (n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    }
    chatTime.timeFrame = function() {
      var geo = [[0, 5], [6, 8], [9, 11], [12, 13], [14, 16], [17, 18], [19, 21], [22, 23]]
      var frame = ['凌晨', '早上', '上午', '中午', '下午', '傍晚', '晚上', '深夜']
      return frame[geo.indexOf(geo.filter(function(v) {
        return v[0] <= chatTime._argHour && v[1] >= chatTime._argHour
      })[0])]
    }
    chatTime.formatDate = function(formatString, isTimeFrame = false){
      function format (e) { return e < 10 ? ('0' + e) : e }
      var _date = getDate(timestamp)
      var time = { timestamp:timestamp }
      time.YYYY = _date.getFullYear()
      time.MM = format(_date.getMonth() + 1)
      time.DD = format(_date.getDate())
      time.hh = format(_date.getHours())
      time.mm = format(_date.getMinutes())
      time.ss = format(_date.getSeconds())
      var res = ''
      formatString.trim().split(' ').forEach(function(value, index){
        if (!value) return
        var l = value.split('-')
        var c = value.split(':')
        if (index) res += ' '
        if (index && isTimeFrame) res += chatTime.timeFrame().toString()
        if (l.length === 1) {
          c.forEach(function(val, idx){
            if (idx) res += ':'
            res += time[val]
          })
          if (!index && isTimeFrame) res = chatTime.timeFrame().toString() + res
        } else {
          l.forEach(function(val, idx){
            if (idx) res += '-'
            res += time[val]
          })
        }
      })
      return res
    }
    chatTime.init()

    if (chatTime._nowYear === chatTime._argYear) {
      if (chatTime._nowMonth === chatTime._argMonth) { // 一個月內
        var dayDiff = chatTime._nowDay - chatTime._argDay
        if (dayDiff > 7) {
          return isDetail ? chatTime.formatDate('MM-DD hh:mm', true) : chatTime.formatDate('MM-DD')
        } else if (dayDiff === 1) {
          return isDetail ? '昨天'+chatTime.formatDate('hh:mm', true) : '昨天' + chatTime.formatDate('hh:mm')
        } else if (dayDiff === 2) {
          return isDetail ? '前天' + chatTime.formatDate('hh:mm', true) : '前天' + chatTime.formatDate('hh:mm')
        } else if ([3, 4, 5, 6, 7].indexOf(dayDiff)) {
          return isDetail ? chatTime.week[chatTime._argWeek] + chatTime.formatDate('hh:mm') : chatTime.week[chatTime._argWeek]
        } else if (dayDiff <= 0) {
          return chatTime.formatDate('hh:mm', true)
        }
      } else if (chatTime._nowMonth > chatTime._argMonth) {
        return isDetail ? chatTime.formatDate('MM-DD hh:mm', true) : chatTime.formatDate('MM-DD')
      } else {
        return isDetail ? chatTime.formatDate('MM-DD hh:mm', true) : chatTime.formatDate('MM-DD')
      }
    } else {
      return chatTime.formatDate('YYYY-MM-DD')
    }
  }
  
  module.exports = {
    chatDateFormat : chatDateFormat
  }

相關文章