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

时间:2013-10-31 07:05:51

标签: javascript datetime milliseconds

我的时间是毫秒,但我希望转换后的时间如00:00:00

例如:毫秒= 86400000。我希望在几毫秒内花费多少小时,例如00:00:00

如何在JavaScript中获取它?

20 个答案:

答案 0 :(得分:66)

如何在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))

答案 1 :(得分:35)

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

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

"Out Put Sample"

答案 2 :(得分:15)

我有同样的问题,这就是我最终做的事情:

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

答案 3 :(得分:12)

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

答案 4 :(得分: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))

答案 5 :(得分: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}`;
}

答案 6 :(得分: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`;
}

答案 7 :(得分:2)

这是我的解决方法

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

答案 8 :(得分:1)

my solution

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 will become '7.04 AM'

答案 9 :(得分:1)

以上摘要不适用于超过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;
}

enter image description here

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

答案 10 :(得分:1)

此解决方案使用一个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))

答案 11 :(得分:1)

为我工作

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

答案 12 :(得分: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;
}

答案 13 :(得分:0)

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

使用

(见下面的函数定义)

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

它的编写方式使您可以轻松实现其他单元(例如,我在其中注释了数周的实现),只要您知道它们的价值(以毫秒为单位)。

答案 14 :(得分:0)

格式为 hh:mm:ss,带可选填充

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

大致基于 Chand's answer

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

答案 15 :(得分:0)

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

import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:http/http.dart' as http;

void main() {

runApp(MaterialApp(

home: Home(),

));

}

class Home extends StatelessWidget {

var icon;

var url = "https://jsonplaceholder.typicode.com/photos";

Future getFata() async {

var response = await http.get(url);

if (response.statusCode == 200) {

var jsonData = jsonDecode(response.body);

var name = jsonData[0]["albumId"];

print("hhhhhhhhhhhhhhh" + name);

icon = jsonData[0]["url"];

print(icon);

} else {

print(response.statusCode);

}

}

@override

Widget build(BuildContext context) {

return Scaffold(

body: Column(children: <Widget>[

MaterialButton(

onPressed: () {

getFata();

},

child: Text("do"),

),

Image.network(icon)

]),

);

}

}

答案 16 :(得分:0)

对不起,晚到晚会。接受的答案对我而言并没有帮助,所以我自己写了。

输出:

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

答案 17 :(得分:0)

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

.ui-rating-icon {
    font-size: 15px !important;
    color: #ffab18 !important;
}

一旦拿到琴弦,我就随心所欲地编曲。

答案 18 :(得分:0)

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

Unpooled.copiedBuffer(buffer.array())

答案 19 :(得分:0)

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

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