时间字符串转换为时间戳方法

1.new Date().getTime()

new Date('2021-12-14 10:10:00').getTime()  // 1639447800000

2.Date.parse()

Date.parse('2021-12-14 10:10:00')  // 1639447800000

封装方法

conversionTime(date) {
    let t = ''
    if (date === '') {
      return ''
    }
    if (!date) {
      const oDate = new Date()
      t = Date.parse(oDate)
    } else {
      // 兼容360、ie浏览器, 360、ie只支持'/'时间格式
      typeof date === 'string' && date.indexOf('-') !== -1 && (date = date.replace(/-/g, '/'))
      const oDate = new Date(date)
      t = Date.parse(oDate)
    }
    return t
  }

时间戳转换为字符串

let time = ‘1639440000’
Let timeLength = time.length
Let timeStr = null
if (timeLength === 10) {
    timeStr = new Date(time * 1000)
} else if (timeLength === 13) {
    timeStr = new Date(time)
} else if (timeLength === 19) {
    timeStr = new Date(time)
}
let year = timeStr .getFullYear()
let month = timeStr .getMonth() + 1
let day = timeStr .getDate()
let hour = timeStr .getHours()
let minute = timeStr .getMinutes()
let second = timeStr .getSeconds()
if (month < 10) {
    month = '0' + month
}
if (day < 10) {
   day = '0' + day
}
if (hour < 10) {
    hour = '0' + hour
}
if (minute < 10) {
    minute = '0' + minute
}
if (second < 10) {
    second = '0' + second
}
return `${year}-${month}-${day} ${hour}:${minute}:${second}`

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐