如何在JavaScript中将时间毫秒转换为小时,分钟,秒格式?


81

我的时间以毫秒为单位,但是我希望转换后的时间像00:00:00

例如:以毫秒为单位= 86400000。我想要几毫秒之内的时间,00:00:00

如何在JavaScript中获得它?

Answers:


119

如何通过在javascript中创建函数来做到这一点,如下所示:

function msToTime(duration) {
  var milliseconds = parseInt((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))


我已经使用这种方式将毫秒转换为小时:分钟:秒格式。但是我没有正确获取它。所有毫秒仅给出21:11:05。如何实现呢?
cheliyan 2013年

1
var s = st_date +''+ start; var e = end_date +''+ end; var bits = s.split(/ \ D /); var bits1 = e.split(/ \ D /); var date = new Date(位[0],-位[1],位[2],位[3],位[4],位[5]);var date1 =新日期(bits1 [0],-bits1 [1],bits1 [2],bits1 [3],bits1 [4],bits1 [5]);
cheliyan 2013年

var t1 = date.getTime()var t2 = date1.getTime()var t3 = date1.getTime()-date.getTime(); var秒;var分钟;var毫秒= parseInt((t3%1000)/ 100),秒= parseInt((t3 / 1000)%60),分钟= parseInt((t3 /(1000 * 60))%60),小时= parseInt((t3 /(1000 * 60 * 60))%24); 小时=(小时<10)?“ 0” +小时:小时;分钟=(分钟<10)?“ 0” +分钟:分钟;秒=(秒<10)?“ 0” +秒:秒;持续时间=小时+“:” +分钟+“:” +秒;alert('dur ::'+ t3); alert('duration:'+ duration);
cheliyan 2013年

5
parseInt(string)不是最佳的发言方式。例如,您不能在打字稿中使用它。又为什么是ms / 100?这根本不是一个好答案。
多米尼克'18

1
jsperf.com/test-parseint-and-math-floor楼的方式比parseInt函数更快
马修·瑞格勒

52

将毫秒转换为人类可读的格式。

 function timeConversion(millisec) {

        var seconds = (millisec / 1000).toFixed(1);

        var minutes = (millisec / (1000 * 60)).toFixed(1);

        var hours = (millisec / (1000 * 60 * 60)).toFixed(1);

        var days = (millisec / (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"
        }
    }

“放样”


4
我发现这是最有用的方法,在我的测试中,最佳答案似乎无法很好地解决小时问题,这也为您提供了很多选择。
ak85 '16

21

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

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


16

这个像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”

comment-在负时间不能正常工作,例如-3000应该显示-00:03但返回-1:0-03
阿努

16

这是我的解决方案

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

华丽。谢谢。
安迪

这个问题的最干净答案。
muad-dweeb

1
我将值设置为三元运算符之外的值:s = `${s < 10 ? '0': ''}${s}`
seniorpreacher

8

不好意思,晚到晚会。接受的答案对我而言并没有切合实际,所以我自己写了它。

输出:

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

谢谢男人,这就是我想要的。不得不稍作调整以显示“ 0h 0m 10s”等,但其他方式又干净又简单
HazeyAce

我开始写自己的书,然后我想,肯定有人已经完成了:)。谢谢!
奔小号

6

以上代码段不适用于超过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


1
要获得更人性化的输出,您可以返回类似以下内容的内容:return((h +'').length === 1?'0'+ h:h)+':'+('0'+ m).substr(- 2)+':'+('0'+ s).substr(-2);
维塔尔

@Vitall只需使用return (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);,因为用数学比一堆字符串操作更好。
米奇·麦克马伯斯

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

1
有人可能会觉得有用。
KevinOrfas

1
JS正在向TypeScript发展。这可能很快就会成为有效的JS。:-)
N8allan

2

我最多只需要一天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);

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


2

此解决方案使用一个function将毫秒分割为parts object,然后使用另一个function格式化parts 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))


2

为我工作

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

2

用于人类可读输出的人类可读代码,您可以将其扩展到十亿分之一秒或十亿分之一秒或非常直观的内容。显然,您希望将其转换为函数,然后重新使用其中一些中间模调用。

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

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 '


1

我为我工作,因为我使用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
}

说明您的代码,没有解释的代码是错误的代码。
Islam Elshobokshy

谢谢您的建议,我肯定会解释我的解决方案
Sneha Morye

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

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

  ...
}

一旦得到了琴弦,我就可以根据自己的需要创作它们了。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.