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

138
我有一段以毫秒为单位的时间,我想将它转换成“HH:MM:SS”格式。它应该会环绕,例如当milliseconds = 86400000时,我希望得到00:00:00
27个回答

4

我最近遇到了这种情况,我的重点是保持代码的可读性和可重用性。

使用方法

(请查看下面的函数定义)

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} 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: allocate(604800000), // Uncomment for weeks
        days: allocate(86400000),
        hours: allocate(3600000),
        minutes: allocate(60000),
        seconds: allocate(1000),
        ms: ms // remainder
    }
}

这段代码的编写方式非常巧妙,只要你知道其他单位的毫秒值(例如我在注释中取消了星期的实现),就可以轻松地实现其他单位。


4

//以下内容是用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`;
}

3

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

我喜欢这个,但是如果分钟数小于10怎么办?你能添加填充吗? - ndtreviv
@ndtreviv,不,它不包括在内,但是你可以很容易地添加它,看看Shady的回答。 - Mustapha-Belkacim
@ndtreviv 填充:https://dev59.com/DWIj5IYBdhLWcg3w_5vl#67462589/ - Sinjai

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

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

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
有人可能会发现它有用。 - Anastasis
1
JS正在向TypeScript发展。这很快可能会成为有效的JS。:-) - N8allan

2

可以使用毫秒构造一个Date对象:

const date = new Date(0, 0, 0, 0, 0, 0, milliseconds);

在你的问题中,你提到毫秒应该在86400000时“绕回”。由于我们知道一天有86400000毫秒,我们可以简单地从日期对象中获取时间,并忽略日期中的其他部分。时间可以以任何格式获得。你需要的就是与英国使用的相匹配的格式,本地化 en-GB:
const hms = d.toLocaleTimeString('en-GB');

聪明,但仅适用于小于24小时的持续时间。 - MHebes
1
啊,我没看清楚操作。已经点赞了 :) - MHebes

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'


这受操作系统中罗马尼亚设置的影响。我得到了“上午7:04”。 - HolgerJeromin

0

从@dusht的重构到ES6+和更多的函数式:

const addPrefix = time => time < 10 ? '0' + time : time;
const toHours = time => addPrefix(Math.floor((time / (1000 * 60 * 60)) % 24));
const toMinutes = time => addPrefix(Math.floor((time / (1000 * 60)) % 60));
const toSeconds = (ime => addPrefix(Math.floor((time / 1000) % 60));
const toMiliseconds = time => Math.floor((time % 1000) / 100);


const milisecondToHoursAndMinute = time => {
  const hours = toHours(time);
  const minutes = toMinutes(time);
  const seconds = toSeconds(time);
  const miliseconds = toMiliseconds(time);

  return `${hours}:${minutes}:${seconds}.${miliseconds}`
}

0
let dateTimeStr = new Date(1949778000);
dateTimeStr = Math.floor(dateTimeStr/86400000) +' days '+ dateTimeStr.getHours() +' hours '+ dateTimeStr.getMinutes() +' minutes '+ dateTimeStr.getSeconds() +' seconds';
console.log(dateTimeStr);

如果您不需要计算天数,可以跳过它们的计算。

"22天16小时36分钟18秒"


请注意,使用这种技术时要小心,因为它没有考虑到时区偏移。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接