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}`
    }
    
  • 相关阅读:
    互联网博物馆
    CSS简介和CSS选择器
    perl 面向对象 use base
    mysql tcp 4层负载
    mysql tcp 4层负载
    mysql Emoji表情字符集转换
    mysql Emoji表情字符集转换
    html submit 登录
    html submit 登录
    haroxy hdr
  • 原文地址:https://www.cnblogs.com/guojiabing/p/11212466.html
Copyright © 2011-2022 走看看