时间戳与时间类型的相互转换

博客主要介绍了JavaScript中时间戳与时间类型的转换及相关时间戳的获取方法,包括时间戳转时间类型、时间字符转时间戳,还提及获取现在、今天、前一天和后一天的时间戳。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 时间戳转时间类型

例:var timestamp=1113898961;//注意这里一定是数字类型,否则下面会报错 :"Invalid Date"

 

new Date(timestamp*1000)  // Tue Apr 19 2005 16:22:41 GMT+0800 (中国标准时间)

【js时间戳精确到毫秒,所以我的这里需要乘以1000转换】

 

new Date(timestamp).toLocaleString()   // 2005/4/19 下午4:22:41

2 时间字符转时间戳

new Date('2005/4/19 12:00:00').getTime();   // 1113883200000
new Date('2019-03-22 10:07:46').getTime();  // 1553220466000
new Date('2005/4/19 上午12:00:00').getTime()  //  NAN

3 获取现在的年月日时分秒的时间戳:

new Date().getTime()  //1553133130851 (ms)

4 获取今天年月日的时间戳:

var time=new Date();
time.toLocaleDateString()// 2019/3/21
console.log((new Date(time.toLocaleDateString()).getTime()) * 0.001); //1549209600(s)

5 获取前一天 后一天

console.log(new Date((new Date(time.toLocaleDateString()).getTime()) - 24 * 60 * 60 * 1000).toLocaleDateString());//2019/3/20

console.log(new Date((new Date(time.toLocaleDateString()).getTime()) + 24 * 60 * 60 * 1000).toLocaleDateString());//2019/3/22

前后时间戳

console.log(new Date((new Date(time.toLocaleDateString()).getTime()) - 24 * 60 * 60 * 1000));//1553011200000 (ms)
console.log(new Date((new Date(time.toLocaleDateString()).getTime()) + 24 * 60 * 60 * 1000));//1553184000000 (ms)

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值