时间戳转换

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

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

  console.log(timestamp1);

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

console.log(timestamp2);

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

console.log(timestamp3);

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

console.log(timetamp4);

二,时间戳转时间

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

console.log(timestamp4)

可以通过分别获取时间的年月日进行拼接,比如:

function getdate() {

            var now = new Date(),

                y = now.getFullYear(),

                m = now.getMonth() + 1,

                d = now.getDate();

            return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);

        }

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

推荐阅读更多精彩内容