时间戳与字符串时间互相转换

532 阅读1分钟

获取时间戳

const date = new Date().getTime()//1652146774785

通过时间戳来控制时间段

  1. 先获取当日零点的时间戳。
const time = new Date()
const Y = time.getFullYear().toString()
const M = (time.getMonth() + 1).toString().padStart(2, '0')
const D = time.getDate().toString().padStart(2, '0')
const time_stamp = + new Date(`${Y}-${M}-${D}`)
//这个时间戳对应的时间是当天早上八点,2022-05-10 08:00:00
console.log(time_stamp)//1652140800000
// 当天零点时间需要减去 60 * 60 * 8 * 1000
zeroTimeStamp = time_stamp - 60 * 60 * 8 * 1000
console.log(zeroTimeStamp)//1652112000000
  1. 获取三天前的时间戳。
const day = 60 * 60 * 24 * 1000//一天的时间毫秒
const threeDays = zeroTimeStamp - (day * 3)//1651852800000
  1. 再使用下面的时间戳格式化日期

时间戳--->字符串时间

const toTimestr = (time_stamp) => {
            time_stamp = Number((time_stamp + '').padEnd(13, '0'))
            const time = new Date(time_stamp)
            const Y = time.getFullYear()
            const M = (time.getMonth() + 1).toString().padStart(2, '0')
            const D = time.getDate().toString().padStart(2, '0')
            const h = time.getHours().toString().padStart(2, '0')
            const m = time.getMinutes().toString().padStart(2, '0')
            const s = time.getSeconds().toString().padStart(2, '0')
            return `${Y}-${M}-${D} ${h}:${m}:${s}`
        }

字符串时间--->时间戳

const res = + new Date('2022-02-12')//这个时间戳对应的时间是当天早上八点