• javascript 时间与时间戳的转换


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

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

    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)}`; 
    }
  • 相关阅读:
    sql2slack alash3al 开源的又个轻量级工具
    pgspider fetchq 扩展docker镜像
    godns 集成coredns 的demo
    godns 简单dnsmasq 的dns 替换方案
    aviary.sh 一个基于bash的分布式配置管理工具
    使用coredns 的template plugin实现一个xip 服务
    nginx 代理 coredns dns 服务
    基于nginx proxy dns server
    几个不错的geodns server
    spring boot rest api 最好添加servlet.context-path
  • 原文地址:https://www.cnblogs.com/lmyt/p/6013097.html
Copyright © 2020-2023  润新知