js获取时间

const t1 = new Date().valueOf() // 第一种,推荐
const t2 = new Date().getTime() // 第二种,推荐
const t3 = Date.parse(new Date()) // 第三种,不推荐,精度差一些

const t = new Date('日期时间').valueOf() // 方法一
const t1 = new Date('日期时间').getTime() // 方法二
const t2 = new Date('2022-04-15').valueOf() // 1649980800000
const t3 = new Date('2022-04-15 12:15:36').valueOf() // 1649996136000
const t4 = new Date('2022-04-15').getTime() // 1649980800000
const t5 = new Date('2022-04-15 12:15:36').getTime() // 
image.png
//  获取时间
// console.log('昨天:', this.getDay(-1, 7200000))
// console.log('今天:', this.getDay(0, 3600000))
// console.log('明天:', this.getDay(1, 3600000))
// console.log('一周后:', this.getDay(7, 7200000)
const  getDay  = (day,hours) => {
  let _hours = hours?hours:3600000
  var date = new Date()
  var targetday = date.getTime() + 1000 * 60 * 60 * 24 * day + _hours
  date.setTime(targetday)
  const Y = date.getFullYear() + '-'
  const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) + '-' : date.getMonth() + 1 + '-'
  const D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
  const h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
  const m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':'
  const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()    
  if(day == 1){
    return  {time:Y + M + D + '00:00:00',num:Date.parse(Y + M + D + '00:00:00')}
  }else{
    return  {time:Y + M + D + h + m + s,num:Date.parse(Y + M + D + h + m + s)}
  }
  //  time 时间  num 时间戳
};

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容