javascript 时间与时间戳的转换

一:时间转时间戳:javascript得到时间戳的方法有五种,都是经过实例化时间对象 new Date() 来进一步获取当前的时间戳javascript

1.var timestamp1 = Date.parse(new Date()); // 结果:1477808630000 不推荐这种办法,毫秒级别的数值被转化为000java

  console.log(timestamp1);浏览器

2.var timestamp2 = (new Date()).valueOf(); // 结果:1477808630404 经过valueOf()函数返回指定对象的原始值得到准确的时间戳值函数

console.log(timestamp2);spa

3.var timestamp3 = new Date().getTime(); // 结果:1477808630404 ,经过原型方法直接得到当前时间的毫秒值,准确code

console.log(timestamp3);对象

4.var timetamp4 = Number(new Date()) ; //结果:1477808630404 ,将时间转化为一个number类型的数值,即时间戳blog

console.log(timetamp4);ip

5.ES5给Date提供了一种获取时间戳的新特性  
var timetamp5 = Date.now();                   //结果:1477808630404 get

console.log(timetamp5);

打印结果 以下:

 

 

二,时间戳转时间

var timestamp4 = new Date(1472048779952);//直接用 new Date(时间戳) 格式转化得到当前时间

console.log(timestamp4);

console.log(timestamp4.toLocaleDateString().replace(/\//g, "-") + " " + timestamp4.toTimeString().substr(0, 8)); //再利用拼接正则等手段转化为yyyy-MM-dd hh:mm:ss 格式

效果以下:

 

不过这样转换在某些浏览器上会出现不理想的效果,由于toLocaleDateString()方法是因浏览器而异的,好比 IE为2016年8月24日 22:26:19 格式 搜狗为Wednesday, August 24, 2016 22:39:42

 

能够经过分别获取时间的年月日进行拼接,好比:

function getdate() {
            var now = new Date(),
                y = now.getFullYear(),
                m = ("0" + (now.getMonth() + 1)).slice(-2),
                d = ("0" + now.getDate()).slice(-2);
            return `${y}-${m}-${d} ${now.toTimeString().substr(0, 8)}`; }
相关文章
相关标签/搜索