美文网首页
时间戳转换

时间戳转换

作者: 洋洋_13dc | 来源:发表于2019-05-31 14:51 被阅读0次

    一:时间转时间戳: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);

            }

    相关文章

      网友评论

          本文标题:时间戳转换

          本文链接:https://www.haomeiwen.com/subject/ksawtctx.html