小程序之将时间戳转换为时间

168 阅读1分钟

formatTime.js模块

//将时间戳转换为时间
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime
}

调用使用

//logs.js
const formatTimeService = require('../../utils/formatTime.js')  //引入formatTime模块

Page({
  data: {
    logs: []
  },
  onLoad: function () {
    this.setData({
      logs: (wx.getStorageSync('logs') || []).map(log => {
         // log是时间戳
        return formatTimeService.formatTime(new Date(log))
      })
    })
  }
})