zoukankan      html  css  js  c++  java
  • JS时间戳与时间字符串之间的相互转换

    时间字符串 转 时间戳

      /**
       * 时间字符串 转 时间戳
       * @param {String} time_str 时间字符串(格式"2014-07-10 10:21:12")
       * @returns {Number} 10位数的时间戳(秒值:1404958872000)
       */
    const toTimestamp = time_str => +new Date(time_str) / 1000
    
    • 默认转化后为Number类型后获得的是时间的毫秒数值,需求是要10位数的秒值,所以需要除以1000

    • JavaScript中可以在某个元素前使用 '+' 号,这个操作是将该元素转换成Number类型,如果转换失败,那么将得到 NaN

    • +new Date() 将会调用 Date.prototype 上的valueOf()方法

    • 等效代码如下:

      • console.log(+new Date());
      • console.log(new Date().getTime());
      • console.log(new Date().valueOf());
      • console.log(new Date() * 1);

    时间戳 转 时间字符串

    /**
     * 时间戳 转 时间字符串
     * @param {Number} time_stamp 10位数的时间戳(秒值:1404958872)
     * @returns {String} 时间字符串 (格式"2014-07-10 10:21:12")
     */
    const toTimestr = time_stamp => {
        const time = new Date(time_stamp * 1000);
        const Y = time.getFullYear()
        const M = (time.getMonth() + 1).toString().padStart(2, '0')
        const D = time.getDate().toString().padStart(2, '0')
        const h = time.getHours().toString().padStart(2, '0')
        const m = time.getMinutes().toString().padStart(2, '0')
        const s = time.getSeconds().toString().padStart(2, '0')
        return `${Y}/${M}/${D} ${h}:${m}:${s}`
    }
    
  • 相关阅读:
    [Java] 编写第一个java程序
    [Java] 环境变量设置
    [ActionScript 3.0] 常用的正则表达式
    [ActionScript 3.0] 正则表达式
    Python学习之==>URL编码解码&if __name__ == '__main__'
    Python学习之==>面向对象编程(一)
    Linux下安装redis-4.0.10
    Linux下编译安装Python-3.6.5
    Python学习之==>发送邮件
    Python学习之==>网络编程
  • 原文地址:https://www.cnblogs.com/guojiabing/p/11212466.html
Copyright © 2011-2022 走看看