一、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]