美文网首页
js时间戳转换成日期

js时间戳转换成日期

作者: smallzip | 来源:发表于2019-07-12 11:25 被阅读0次

实现简单的时间戳转换,造一次轮子,后期复用省时省力。

// 转换时间戳
console.log(filterTime(new Date().getFullYear()));  // 1970-01-01 08:00:19
console.log(filterTime(Date.now()));  // 2019-07-12 11:18:26
console.log(filterTime(Date.now()/1000));  // 2019-07-12 11:18:26
console.log(filterTime('1562899318'));  // 2019-07-12 10:41:00
console.log(filterTime('1562899318000'));  // 2019-07-12 10:41:00
console.log(filterTime('2019-07-12 11:10:10'));  // 2019-07-12 11:10:00
console.log(filterTime('2019-7-1 1:9:10'));  // 2019-07-01 01:09:00
console.log(filterTime(Date.now(),'/'));  // 2019/07/12 11:18:26
console.log(filterTime(Date.now(),'-','/'));  // 2019-07-12 11/18/26



// 时间戳转换   
// 参数1:date  [转换的日期]
// 参数2:  spare  [年月日数间隔符]
// 参数3:timeSpare [时分秒间隔符]
function filterTime(date, spare = '-', timeSpare = ':') {
      // 补零
      function fix(i) {
        typeof i !== 'number' ? i = parseInt(i):null
        return i < 10 ? `0${i}` : i
      }
      // 生成时间
      function time(t, spare = '-', timeSpare = ':') {
        let [y, m, d, h, mi, ms] = [
          new Date(t).getFullYear(),
          new Date(t).getMonth() + 1,
          new Date(t).getDate(),
          new Date(t).getHours(),
          new Date(t).getMinutes(),
          new Date(t).getSeconds()
        ]
        return `${y}${spare}${fix(m)}${spare}${fix(d)} ${fix(h)}${timeSpare}${fix(mi)}${timeSpare}${fix(ms)}`
      }
      // 获取长度
      let len = null
      if(typeof date === 'number'){
        date = parseInt(date)
        len = date.toString().length
      } else{
        len = date.length
        len == 13 ? date = parseInt(date):null
      }
      if (len === 10) {
        return time(date * 1000, spare, timeSpare)
      } else if (len === 13) {
        return time(date, spare, timeSpare)
      } else {
        return time(date, spare, timeSpare)
      }
    }

相关文章

  • 获取时间,时间与时间戳之间的转换

    一、JS获取当前时间,时间与时间戳之间的转换 获取当前时间 时间与时间戳之间的转换 将时间戳转换成日期格式 将日期...

  • JS之日期转换

    时间戳转换成日期格式

  • Flutter 学习 之 时间转换工具类

    日期转换成时间戳 时间戳转时间格式 时间戳转字符串格式 将传进来的 时间戳/日期格式 转成 DateTime 格式...

  • Flutter 处理时间

    日期转换成时间戳 时间戳转时间格式 时间戳转字符串格式 将传进来的 时间戳/日期格式 转成 DateTime 格式...

  • js时间戳转换成日期

    实现简单的时间戳转换,造一次轮子,后期复用省时省力。

  • Unix时间戳与日期格式的相互转化

    1. 将时间戳转换成日期格式 2. 将日期格式转换为时间戳

  • 时间整合

    PHP时间戳和日期相互转换在php中我们要把时间戳转换日期可以直接使用date函数来实现,如果要把日期转换成时间戳...

  • js时间戳与日期格式的相互转换

    今天看到个小文章总结一下js中时间戳与日期格式的相互转换,如果有用的话就搜藏一下; 将时间戳转换成日期格式:fun...

  • js倒计时天时分秒

    倒计时实现 1 获取当前的时间戳2 获取截止日期的时间戳3 截止日期时间戳减去当前日期时间戳转换成天时分秒 通...

  • 时间戳问题

    js时间戳转换成time:new Date(parseInt(8位时间戳 )* 1000).toLocalStri...

网友评论

      本文标题:js时间戳转换成日期

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