JavaScript 实现毫秒转换为时长

毫秒数(时间戳)转换为持续时长,或者转换成日期

直接上代码

/** transfer time */
  const transferTime = (milliseconds = 0, type) => {
    // get duration
    const getDurations = (milliseconds) => {
      // days
      const days = milliseconds / 1000 / 60 / 60 / 24
      const daysRound = Math.floor(days)
      const daysStr = `${daysRound > 0 ? `${daysRound}` : ''}`
      // hours
      const hours = milliseconds / 1000 / 60 / 60 - (24 * daysRound)
      const hoursRound = Math.floor(hours)
      const hoursStr = `${hoursRound > 0 ? `${hoursRound}` : ''}`
      // minutes
      const minutes = milliseconds / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound)
      const minutesRound = Math.floor(minutes)
      const minutesStr = `${minutesRound > 0 ? `${minutesRound}` : ''}`
      // seconds
      const seconds = milliseconds / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound)
      const secondsRound = Math.floor(seconds)
      const secondsStr = `${secondsRound > 0 ? `${secondsRound}` : ''}`
      // ms
      const ms = milliseconds - (24 * 60 * 60 * 1000 * daysRound) - (60 * 60 * 1000 * hoursRound) - (60 * 1000 * minutesRound) - (secondsRound * 1000)
      const msStr = `${ms > 0 ? `${ms}毫秒` : ''}`

      const str = `${daysStr}${hoursStr}${minutesStr}${secondsStr}${msStr}`
      return str
    }

    // get date
    const getDate = (milliseconds) => {
      let date = new Date(milliseconds/1);
      // year
      const year = date.getFullYear()
      // month
      let month = date.getMonth() + 1;
      month = (month < 10 ? '0' + month : month);
      // day
      let day = date.getDate();
      day = (day < 10 ? '0' + day : day);
      // hour
      let hours = date.getHours();
      hours = (hours < 10 ? '0' + hours : hours);
      // minutes
      let minutes = date.getMinutes();
      minutes = (minutes < 10 ? '0' + minutes : minutes);
      // seconds
      let seconds = date.getSeconds();
      seconds = (seconds < 10 ? '0' + seconds : seconds);

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }

    if (type === 'duration') {
      return getDurations(milliseconds)
    }
    if (type === 'date') {
      return getDate(milliseconds)
    }
  }

验证一下

const time = '8483424010';
console.log(transferTime(time, 'date'))
console.log(transferTime(time, 'duration'))

控制台打印结果

1970-04-09 12:30:24
984302410毫秒

ok了

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值