new Date()格式化时间转时间戳及时间戳转正常时间方法

首先说一下如何使用new Date()将正常时间转换成时间戳:

//方法一
var timestamp = (new Date()).getTime(); //如果想获取2019-01-01的时间戳只需要var timestamp = (new Date(‘2019-01-01’)).getTime(); 
console.log(timestamp); //1495302061441   //这边关于时间戳的长度有说法,当时间单位为秒时,数字时间戳的长度是10位,当时间单位为毫秒时,数字时间戳的长度时13位

//方法二
var timestamp2 = (new Date()).valueOf();
console.log(timestamp2); //1495302061447

//方法三
var timestamp3 = +new Date();
console.log(timestamps); //1577939689256

下面说一下如何将时间戳转换为正常时间,目前我所遇到的的情形都是13位时间戳(10位的时间戳可能在转换之前需要timestamp*1000,请查阅相关资料不在本文讨论范围内)

function timestampToTime(value){
   var date=new Date(value);
   var Y= date.getFullYear() + '-';
   var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
   var D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate());
   return Y+M+D; 
}

参考地址:https://blog.csdn.net/guyu96/article/details/81629189

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容