How to convert time milliseconds to hours, min, sec format in JavaScript?

后端 未结 16 2340
渐次进展
渐次进展 2020-11-29 02:28

I have the time as milliseconds, but I want the time after conversion like 00:00:00.

Ex: In milliseconds=86400000. I want how many hours in that millise

相关标签:
16条回答
  • 2020-11-29 03:10

    The above snippets don't work for cases with more than 1 day (They are simply ignored).

    For this you can use:

    function convertMS(ms) {
        var d, h, m, s;
        s = Math.floor(ms / 1000);
        m = Math.floor(s / 60);
        s = s % 60;
        h = Math.floor(m / 60);
        m = m % 60;
        d = Math.floor(h / 24);
        h = h % 24;
        h += d * 24;
        return h + ':' + m + ':' + s;
    }
    

    Thanks to https://gist.github.com/remino/1563878

    0 讨论(0)
  • 2020-11-29 03:10

    Based on @Chand answer. This is the implementation in Typescript. A bit safer than coercing types in JS. If you remove the type annotation should be valid JS. Also using new string functions to normalise the time.

    function displayTime(millisec: number) {
     const normalizeTime = (time: string): string => (time.length === 1) ? time.padStart(2, '0') : time;
    
     let seconds: string = (millisec / 1000).toFixed(0);
     let minutes: string = Math.floor(parseInt(seconds) / 60).toString();
     let hours: string = '';
    
     if (parseInt(minutes) > 59) {
       hours = normalizeTime(Math.floor(parseInt(minutes) / 60).toString());
       minutes = normalizeTime((parseInt(minutes) - (parseInt(hours) * 60)).toString());
     }
     seconds = normalizeTime(Math.floor(parseInt(seconds) % 60).toString());
    
     if (hours !== '') {
        return `${hours}:${minutes}:${seconds}`;
     }
       return `${minutes}:${seconds}`;
    }
    
    0 讨论(0)
  • 2020-11-29 03:12

    Worked for me

    msToTime(milliseconds) {
        //Get hours from milliseconds
        var hours = milliseconds / (1000*60*60);
        var absoluteHours = Math.floor(hours);
        var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;
    
        //Get remainder from hours and convert to minutes
        var minutes = (hours - absoluteHours) * 60;
        var absoluteMinutes = Math.floor(minutes);
        var m = absoluteMinutes > 9 ? absoluteMinutes : '0' +  absoluteMinutes;
    
        //Get remainder from minutes and convert to seconds
        var seconds = (minutes - absoluteMinutes) * 60;
        var absoluteSeconds = Math.floor(seconds);
        var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;
    
        return h == "00" ? m + ':' + s : h + ':' + m + ':' + s;
    }
    
    0 讨论(0)
  • 2020-11-29 03:14

    I needed time only up to one day, 24h, this was my take:

    const milliseconds = 5680000;
    
    const hours = `0${new Date(milliseconds).getHours() - 1}`.slice(-2);
    const minutes = `0${new Date(milliseconds).getMinutes()}`.slice(-2);
    const seconds = `0${new Date(milliseconds).getSeconds()}`.slice(-2);
    
    const time = `${hours}:${minutes}:${seconds}`
    console.log(time);

    you could get days this way as well if needed.

    0 讨论(0)
  • 2020-11-29 03:16

    This solution uses one function to split milliseconds into a parts object, and another function to format the parts object.

    I created 2 format functions, one as you requested, and another that prints a friendly string and considering singular/plural, and includes an option to show milliseconds.

    function parseDuration(duration) {
      let remain = duration
    
      let days = Math.floor(remain / (1000 * 60 * 60 * 24))
      remain = remain % (1000 * 60 * 60 * 24)
    
      let hours = Math.floor(remain / (1000 * 60 * 60))
      remain = remain % (1000 * 60 * 60)
    
      let minutes = Math.floor(remain / (1000 * 60))
      remain = remain % (1000 * 60)
    
      let seconds = Math.floor(remain / (1000))
      remain = remain % (1000)
    
      let milliseconds = remain
    
      return {
        days,
        hours,
        minutes,
        seconds,
        milliseconds
      };
    }
    
    function formatTime(o, useMilli = false) {
      let parts = []
      if (o.days) {
        let ret = o.days + ' day'
        if (o.days !== 1) {
          ret += 's'
        }
        parts.push(ret)
      }
      if (o.hours) {
        let ret = o.hours + ' hour'
        if (o.hours !== 1) {
          ret += 's'
        }
        parts.push(ret)
      }
      if (o.minutes) {
        let ret = o.minutes + ' minute'
        if (o.minutes !== 1) {
          ret += 's'
        }
        parts.push(ret)
    
      }
      if (o.seconds) {
        let ret = o.seconds + ' second'
        if (o.seconds !== 1) {
          ret += 's'
        }
        parts.push(ret)
      }
      if (useMilli && o.milliseconds) {
        let ret = o.milliseconds + ' millisecond'
        if (o.milliseconds !== 1) {
          ret += 's'
        }
        parts.push(ret)
      }
      if (parts.length === 0) {
        return 'instantly'
      } else {
        return parts.join(' ')
      }
    }
    
    function formatTimeHMS(o) {
      let hours = o.hours.toString()
      if (hours.length === 1) hours = '0' + hours
    
      let minutes = o.minutes.toString()
      if (minutes.length === 1) minutes = '0' + minutes
    
      let seconds = o.seconds.toString()
      if (seconds.length === 1) seconds = '0' + seconds
    
      return hours + ":" + minutes + ":" + seconds
    }
    
    function formatDurationHMS(duration) {
      let time = parseDuration(duration)
      return formatTimeHMS(time)
    }
    
    function formatDuration(duration, useMilli = false) {
      let time = parseDuration(duration)
      return formatTime(time, useMilli)
    }
    
    
    console.log(formatDurationHMS(57742343234))
    
    console.log(formatDuration(57742343234))
    console.log(formatDuration(5423401000))
    console.log(formatDuration(500))
    console.log(formatDuration(500, true))
    console.log(formatDuration(1000 * 30))
    console.log(formatDuration(1000 * 60 * 30))
    console.log(formatDuration(1000 * 60 * 60 * 12))
    console.log(formatDuration(1000 * 60 * 60 * 1))

    0 讨论(0)
  • 2020-11-29 03:16

    If you're using typescript, this could be a good thing for you

    enum ETime {
      Seconds = 1000,
      Minutes = 60000,
      Hours = 3600000,
      SecInMin = 60,
      MinInHours = 60,
      HoursMod = 24,
      timeMin = 10,
    }
    
    interface ITime {
      millis: number
      modulo: number
    }
    
    const Times = {
      seconds: {
        millis: ETime.Seconds,
        modulo: ETime.SecInMin,
      },
      minutes: {
        millis: ETime.Minutes,
        modulo: ETime.MinInHours,
      },
      hours: {
        millis: ETime.Hours,
        modulo: ETime.HoursMod,
      },
    }
    
    const dots: string = ":"
    
    const msToTime = (duration: number, needHours: boolean = true): string => {
      const getCorrectTime = (divider: ITime): string => {
        const timeStr: number = Math.floor(
          (duration / divider.millis) % divider.modulo,
        )
    
        return timeStr < ETime.timeMin ? "0" + timeStr : String(timeStr)
      }
    
      return (
        (needHours ? getCorrectTime(Times.hours) + dots : "") +
        getCorrectTime(Times.minutes) +
        dots +
        getCorrectTime(Times.seconds)
      )
    }
    
    0 讨论(0)
提交回复
热议问题