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

你可能感兴趣的:(new Date()格式化时间转时间戳及时间戳转正常时间方法)