js获取时间戳

一、Date.now()   精确到毫秒 13位

// 获取当前时间戳
const timestamp = Date.now()
console.log(timestamp)   //1685632984861

二、getTime()   精确到毫秒 13位

// 获取当前时间戳
const timestamp = new Date().getTime();
console.log(timestamp);
 
// 获取自定义时间戳 
// 1、只传日期不传时间(后面是该时间戳的时间)
const t1 = new Date('2023-06-01').getTime()  //[2023-06-01 08:00:00]
// 2、如果日期没有补0
const t2 = new Date('2023-6-01').getTime()   //[2023-06-01 00:00:00]
// 3、如果是传斜杠格式(补不补0是一样的)
const t3 = new Date('2023/06/01').getTime()  //[2023-06-01 00:00:00]

// 4、传了日期+时间就得到该时间的时间戳
const t4 = new Date('2023-06-01 12:00:00').getTime() // [2023-06-01 12:00:00]
const t5 = new Date('2023/6/1 12:00:00').getTime()   // [2023-06-01 12:00:00]

三、+new Date()   精确到毫秒 13位

// 获取当前时间戳
const timestamp = +new Date();
console.log(timestamp);
 
// 获取今天0点(比如今天是[2023-06-01],那么就获取到[2023-06-01 00:00:00]的时间戳)
const timestamp = new Date().setHours(0, 0, 0, 0)
// 获取今天24点(比如今天是[2023-06-01],那么就获取到[2023-06-02 00:00:00]的时间戳)
const timestamp = new Date().setHours(24, 0, 0, 0)

// 获取近七天时间戳
// 用今天0点的时间戳,减去6天的毫秒数即可   每天的毫秒数为24 * 60 * 60 * 1000
// 比如今天是[2023-06-07],那么就获取到[2023-06-01 00:00:00]的时间戳
const sevenDaysBefore = new Date().setHours(0, 0, 0, 0) - 6 * 24 * 60 * 60 * 1000

四、Date.parse(new Date())   精确到秒 13位

// 获取当前时间戳
const timestamp = Date.parse(new Date());
console.log(timestamp);

// 获取自定义时间戳 
const t1 = Date.parse("2023-06-01")   //[2023-06-01 08:00:00]
const t2 = Date.parse("2023-6-1")     //[2023-06-01 00:00:00]
const t3 = Date.parse("2023/6/1")     //[2023-06-01 00:00:00]
const t4 = Date.parse("2023-06-01 12:00:00") //[2023-06-01 12:00:00]
const t5 = Date.parse("2023/6/1 12:00:00")   //[2023-06-01 12:00:00]

五、valueOf()   精确到毫秒 13位

// 获取当前时间戳
const timestamp = (new Date()).valueOf();
console.log(timestamp);

// 获取自定义时间戳 
const t1 = new Date("2023-06-01").valueOf()  // [2023-06-01 08:00:00]
const t2 = new Date("2023-6-1").valueOf()    // [2023-06-01 00:00:00]
const t3 = new Date('2023/6/1').valueOf()    // [2023-06-01 00:00:00]
const t4 = new Date('2023-06-01 12:00:00').valueOf() // [2023-06-01 12:00:00]
const t5 = new Date('2023/6/1 12:00:00').valueOf()   // [2023-06-01 12:00:00]

六、Number(new Date())   精确到毫秒 13位

// 获取当前时间戳
const timestamp = Number(new Date());
console.log(timestamp);

// 获取自定义时间戳 
const t1 = Number(new Date("2023-06-01"));   //[2023-06-01 08:00:00]
const t2 = Number(new Date("2023-6-1"));     //[2023-06-01 00:00:00]
const t3 = Number(new Date("2023/6/1"));     //[2023-06-01 00:00:00]
const t4 = Number(new Date("2023-06-01 12:00:00"));   //[2023-06-01 12:00:00]
const t5 = Number(new Date("2023/6/1 12:00:00"));     //[2023-06-01 12:00:00]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值