112

我有一个毫秒数的时间,我想将它转换为一种HH:MM:SS格式。它应该环绕,milliseconds = 86400000我想得到00:00:00.

4

20 回答 20

166

如何创建这样的函数:

function msToTime(duration) {
  var milliseconds = Math.floor((duration % 1000) / 100),
    seconds = Math.floor((duration / 1000) % 60),
    minutes = Math.floor((duration / (1000 * 60)) % 60),
    hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

  hours = (hours < 10) ? "0" + hours : hours;
  minutes = (minutes < 10) ? "0" + minutes : minutes;
  seconds = (seconds < 10) ? "0" + seconds : seconds;

  return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
console.log(msToTime(300000))

于 2013-10-31T07:11:34.263 回答
74

以毫秒为单位的时间转换为人类可读的格式。

function msToTime(ms) {
  let seconds = (ms / 1000).toFixed(1);
  let minutes = (ms / (1000 * 60)).toFixed(1);
  let hours = (ms / (1000 * 60 * 60)).toFixed(1);
  let days = (ms / (1000 * 60 * 60 * 24)).toFixed(1);
  if (seconds < 60) return seconds + " Sec";
  else if (minutes < 60) return minutes + " Min";
  else if (hours < 24) return hours + " Hrs";
  else return days + " Days"
}

console.log(msToTime(1000))
console.log(msToTime(10000))
console.log(msToTime(300000))
console.log(msToTime(3600000))
console.log(msToTime(86400000))

于 2015-08-24T11:10:29.777 回答
29

我遇到了同样的问题,这就是我最终要做的:

function parseMillisecondsIntoReadableTime(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 + ':' + m + ':' + s;
}


var time = parseMillisecondsIntoReadableTime(86400000);

alert(time);

于 2015-11-25T06:04:54.747 回答
22

这是我的解决方案

let h,m,s;
h = Math.floor(timeInMiliseconds/1000/60/60);
m = Math.floor((timeInMiliseconds/1000/60/60 - h)*60);
s = Math.floor(((timeInMiliseconds/1000/60/60 - h)*60 - m)*60);

// 获取时间格式 00:00:00

s < 10 ? s = `0${s}`: s = `${s}`
m < 10 ? m = `0${m}`: m = `${m}`
h < 10 ? h = `0${h}`: h = `${h}`


console.log(`${s}:${m}:${h}`);
于 2019-08-18T05:49:49.083 回答
19

这个像 youtube 视频一样返回时间

    function getYoutubeLikeToDisplay(millisec) {
        var seconds = (millisec / 1000).toFixed(0);
        var minutes = Math.floor(seconds / 60);
        var hours = "";
        if (minutes > 59) {
            hours = Math.floor(minutes / 60);
            hours = (hours >= 10) ? hours : "0" + hours;
            minutes = minutes - (hours * 60);
            minutes = (minutes >= 10) ? minutes : "0" + minutes;
        }

        seconds = Math.floor(seconds % 60);
        seconds = (seconds >= 10) ? seconds : "0" + seconds;
        if (hours != "") {
            return hours + ":" + minutes + ":" + seconds;
        }
        return minutes + ":" + seconds;
    }

输出:

  • getYoutubeLikeToDisplay(129900) = "2:10"
  • getYoutubeLikeToDisplay(1229900) = "20:30"
  • getYoutubeLikeToDisplay(21229900) = "05:53:50"
于 2016-05-11T16:42:41.827 回答
12

抱歉,派对迟到了。接受的答案并没有为我剪裁,所以我自己写了。

输出:

2h 59s
1h 59m
1h
1h 59s
59m 59s
59s

代码(打字稿):

function timeConversion(duration: number) {
  const portions: string[] = [];

  const msInHour = 1000 * 60 * 60;
  const hours = Math.trunc(duration / msInHour);
  if (hours > 0) {
    portions.push(hours + 'h');
    duration = duration - (hours * msInHour);
  }

  const msInMinute = 1000 * 60;
  const minutes = Math.trunc(duration / msInMinute);
  if (minutes > 0) {
    portions.push(minutes + 'm');
    duration = duration - (minutes * msInMinute);
  }

  const seconds = Math.trunc(duration / 1000);
  if (seconds > 0) {
    portions.push(seconds + 's');
  }

  return portions.join(' ');
}

console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000)              ));
console.log(timeConversion((60 * 60 * 1000)                                 ));
console.log(timeConversion((60 * 60 * 1000)                    + (59 * 1000)));
console.log(timeConversion(                   (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion(                                      (59 * 1000)));
于 2019-11-12T20:48:50.033 回答
7

上面的片段不适用于超过 1 天的案例(它们被简单地忽略)。

为此,您可以使用:

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;
}

在此处输入图像描述

感谢https://gist.github.com/remino/1563878

于 2018-07-03T13:20:18.643 回答
4

我只需要最多一天的时间,24 小时,这是我的看法:

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);

如果需要,您也可以通过这种方式获得几天。

于 2018-11-04T11:51:04.243 回答
3

此解决方案使用一个将function毫秒拆分为.parts objectfunctionparts object

我创建了 2 个格式函数,一个根据您的要求,另一个打印友好的字符串并考虑单数/复数,并包括一个显示毫秒的选项。

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))

于 2018-10-30T13:24:14.827 回答
3

为我工作

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;
}
于 2019-08-16T13:36:39.813 回答
3

用于人类可读输出的人类可读代码,您可以将其扩展到光年或纳秒或非常直观的时间。显然,您希望将其转换为函数并重新使用其中一些中间模调用。

second = 1000 
minute = second * 60
hour = minute * 60 
day = hour * 24

test = 3 * day + 2 * hour + 11 * minute + 58 * second

console.log(Math.floor(test / day))
console.log(Math.floor(test % day / hour))
console.log(Math.floor(test % day % hour / minute))
console.log(Math.floor(test % day % hour % minute / second))
于 2020-05-24T21:17:15.647 回答
2

// 下面是用Typescript写的,应该很容易翻译成JS

function humanReadableDuration(msDuration: int): string {
    const h = Math.floor(msDuration / 1000 / 60 / 60);
    const m = Math.floor((msDuration / 1000 / 60 / 60 - h) * 60);
    const s = Math.floor(((msDuration / 1000 / 60 / 60 - h) * 60 - m) * 60);

    // To get time format 00:00:00
    const seconds: string = s < 10 ? `0${s}` : `${s}`;
    const minutes: string = m < 10 ? `0${m}` : `${m}`;
    const hours: string = h < 10 ? `0${h}` : `${h}`;

    return `${hours}h ${minutes}m ${seconds}s`;
}
于 2021-01-12T03:19:25.367 回答
2

基于@Chand 的回答。这是 Typescript 中的实现。比 JS 中的强制类型安全一点。如果删除类型注释应该是有效的 JS。还使用新的字符串函数来标准化时间。

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}`;
}
于 2018-02-22T16:49:37.880 回答
2

格式hh:mm:ss与可选填充一样

(1:59:5901:59:59)
(1:5901:59)
(默认值:无填充)

大致基于Chand 的回答

function formatMilliseconds(milliseconds, padStart) {
    function pad(num) {
        return `${num}`.padStart(2, '0');
    }
    let asSeconds = milliseconds / 1000;

    let hours = undefined;
    let minutes = Math.floor(asSeconds / 60);
    let seconds = Math.floor(asSeconds % 60);

    if (minutes > 59) {
        hours = Math.floor(minutes / 60);
        minutes %= 60;
    }

    return hours
        ? `${padStart ? pad(hours) : hours}:${pad(minutes)}:${pad(seconds)}`
        : `${padStart ? pad(minutes) : minutes}:${pad(seconds)}`;
}

测试:

let s = 1000;
let m = 60*s;
let h = 60*m;
console.log(formatMilliseconds(1*h));               // 1:00:00
console.log(formatMilliseconds(1*h, true));         // 01:00:00
console.log(formatMilliseconds(59*m + 59*s));       // 59:59
console.log(formatMilliseconds(59*m + 59*s, true)); // 59:59
console.log(formatMilliseconds(9*m + 9*s));         // 9:09
console.log(formatMilliseconds(9*m + 9*s, true));   // 09:09
console.log(formatMilliseconds(5*s));               // 0:05
console.log(formatMilliseconds(5*s, true));         // 00:05
console.log(formatMilliseconds(2400*s));            // 40:00
console.log(formatMilliseconds(2400*s, true));      // 40:00

.
.
.
如果您需要毫秒精度,您可以使用以下方法获得小数部分:

(asSeconds % 1).toFixed(3).substring(1)

您的回报最终会看起来像这样(根据需要将其分解以提高可读性):

`${padStart ? pad(hours) : hours}:${pad(minutes)}:${pad(seconds)}${(asSeconds % 1).toFixed(3).substring(1)}`

可能有更好的方法可以做到这一点,但这种天真的解决方案可以完成工作。

测试:

let asSeconds = 59.5219;
let seconds = Math.floor(asSeconds);
console.log(`${pad(seconds)}${(asSeconds % 1).toFixed(3).substring(1)}`);
// Equivalent to above, without using `pad()`:
//console.log(`${String(seconds).padStart(2, '0')}${(asSeconds % 1).toFixed(3).substring(1)}`);

// Output: 59.522
于 2021-05-09T21:47:11.857 回答
1

我的解决方案

var sunriseMills = 1517573074000;         // sunrise in NewYork on Feb 3, 2018  - UTC time
var offsetCityMills = -5 * 3600 * 1000;   // NewYork delay to UTC 
var offsetDeviceMills =  new Date().getTimezoneOffset() * 60 * 1000 ;  // eg. I live in Romania (UTC+2) >> getTimezoneOffset() = 120

var textTime = new Date(sunriseMills + offsetCityMills + offsetDeviceMills) 
    .toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric' });

textTime 将变为 ' 7.04 AM '

于 2018-02-03T08:26:29.053 回答
1

扩展@Rick的答案,我更喜欢这样的东西:

function msToReadableTime(time){
  const second = 1000;
  const minute = second * 60;
  const hour = minute * 60;

  let hours = Math.floor(time / hour % 24);
  let minutes = Math.floor(time / minute % 60);
  let seconds = Math.floor(time / second % 60);
 

  return hours + ':' + minutes + ":" + seconds;
}
于 2020-12-21T11:56:45.330 回答
0

在我的实现中,我使用了 Moment.js:

export default (value) => 
  const duration = moment.duration(value);

  const milliseconds = duration.milliseconds();
  const seconds = duration.seconds();
  const minutes = duration.minutes();
  const hours = duration.hours();
  const day = duration.days();

  const sDay = `${day}d `;
  const sHours = (hours < 10) ? `0${hours}h ` : `${hours}h `;
  const sMinutes = (minutes < 10) ? `0${minutes}' ` : `${minutes}' `;
  const sSeconds = (seconds < 10) ? `0${seconds}" ` : `${seconds}" `;
  const sMilliseconds = `${milliseconds}ms`;

  ...
}

拿到琴弦后,我就按照自己的意愿编曲。

于 2019-07-04T07:51:17.313 回答
0

我为我工作,因为我使用 javascript 方法 getTime() 得到毫秒 = 1592380675409,它返回 1970 年 1 月 1 日午夜和指定日期之间的毫秒数。

var d = new Date();//Wed Jun 17 2020 13:27:55 GMT+0530 (India Standard Time)
var n = d.getTime();//1592380675409 this value is store somewhere

//function call 
console.log(convertMillisecToHrMinSec(1592380675409));

var convertMillisecToHrMinSec = (time) => {
  let date = new Date(time);
  let hr = date.getHours();
  let min = date.getMinutes();
  let sec = date.getSeconds();

  hr = (hr < 10) ? "0"+ hr : hr;
  min = (min < 10) ? "0"+ min : min;
  sec = (sec < 10) ? "0"+ sec : sec;

  return hr + ':' + min + ":" + sec;//01:27:55
}
于 2020-06-16T14:30:49.857 回答
0

如果您使用的是打字稿,这对您来说可能是件好事

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)
  )
}
于 2019-03-18T16:26:39.873 回答
-1

我最近遇到了这种情况。我的重点是清晰的可读性和可重用性。

利用

(见下面的函数定义)

timeUnits(86400000) // {days: 1, hours: 0, minutes: 0, seconds: 0, ms: 0}

然后你可以使用数据做任何你想做的事情(比如构建一个字符串)。

其他示例:

timeUnits(214870123) // {days: 2, hours: 11, minutes: 41, seconds: 10, ms: 123}
timeUnits('70123') // null

功能

/**
 * Converts milliseconds into greater time units as possible
 * @param {int} ms - Amount of time measured in milliseconds
 * @return {Object|null} Reallocated time units. NULL on failure.
 */
function timeUnits( ms ) {
    if ( !Number.isInteger(ms) ) {
        return null
    }
    /**
     * Takes as many whole units from the time pool (ms) as possible
     * @param {int} msUnit - Size of a single unit in milliseconds
     * @return {int} Number of units taken from the time pool
     */
    const allocate = msUnit => {
        const units = Math.trunc(ms / msUnit)
        ms -= units * msUnit
        return units
    }
    // Property order is important here.
    // These arguments are the respective units in ms.
    return {
        // weeks: (604800000), // Uncomment for weeks
        days: allocate(86400000),
        hours: allocate(3600000),
        minutes: allocate(60000),
        seconds: allocate(1000),
        ms: ms // remainder
    }
}

它以这样一种方式编写,以便您可以轻松地实现其他单元(例如,我在几周内注释掉了实现),只要您知道它们的价值(以毫秒为单位)。

于 2021-08-05T21:31:57.960 回答