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}`
}
posted @ 2019-07-19 12:01  _Jarrett  阅读(3095)  评论(0编辑  收藏  举报