vue 获取当前年月日

moment.js

当前时间戳获取

console.log(Date.now())

console.log(moment(new Date()).valueOf())

const timestamp = +new Date()
console.log(timestamp)

const date = new Date()
const timestamp = date.getTime()
console.log(timestamp)

console.log(Number(new Date())) // Number()

任意日期转时间戳

const timestamp = +new Date("2022-06-08")
console.log(timestamp);

console.log(moment('2022-01-02', 'YYYY-MM-DD').valueOf())

const date = new Date('2022-04-23 8:50:50:123')
const time1 = date.getTime() // 精确到毫秒
const time2 = date.valueOf() // 精确到毫秒
const time3 = Date.parse(date) // 精确到秒,毫秒用000替代
console.log(time1,time2,time3)

注意:获取到的时间戳除以1000就可获得Unix时间戳

时间戳转日期

const date = this.timestampToTime(time1)
console.log(date)

moment(timestamp).format('YYYY-MM-DD HH:mm:ss')
// 年-月-日 时:分:秒
timestampToTime(timestamp) {
    let date = new Date(timestamp) // 时间戳为10位需*1000,13位不需*1000
    let yy = date.getFullYear()
    let mm = this.addZero(date.getMonth() + 1)
    let dd = this.addZero(date.getDate())
    let hh = this.addZero(date.getHours())
    let mf = this.addZero(date.getMinutes())
    let ss = this.addZero(date.getSeconds())
    return `${yy}-${mm}-${dd} ${hh}:${mf}:${ss}`
},

// 判断时间小于10前面加0
addZero(str) {
  return str < 10 ? '0' + str : str
},

Logo

前往低代码交流专区

更多推荐