Javascript秒到分钟和秒


170

这是一个普遍的问题,但我不确定如何解决。下面的代码工作正常。

var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);

var secd = mind % 60;
var seconds = Math.ceil(secd);

但是,当我到达1小时或3600秒时,它将返回0分0秒。如何避免这种情况,让它在所有分钟内返回?

谢谢


那是因为当时间= 3600时,3600%3600始终为0 ...因此,根据您的计算,其他所有内容都将为0。
MSI 2010年

Answers:


338

要获得完整的分钟数,请用总秒数除以60(60秒/分钟):

var minutes = Math.floor(time / 60);

要获得剩余的秒数,请将整分钟乘以60并从总秒数中减去:

var seconds = time - minutes * 60;

现在,如果您也想获得完整的小时数,请先将总秒数除以3600(60分钟/小时·60秒/分钟),然后计算剩余的秒数:

var hours = Math.floor(time / 3600);
time = time - hours * 3600;

然后,您可以计算完整的分钟数和剩余的秒数。

奖金:

使用以下代码漂亮地打印时间(由Dru建议)

function str_pad_left(string,pad,length) {
    return (new Array(length+1).join(pad)+string).slice(-length);
}

var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);

57
通过执行“ var seconds = time%60”来获得剩余的秒数,会更清洁一点。
爱德华·德萨扎

11
@Radio使用添加前导零 function str_pad_left(string,pad,length){ return (new Array(length+1).join(pad)+string).slice(-length); } var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);
德鲁

1
此解决方案不适用于的负值time。例如,如果您输入-1秒,则返回-1分59秒……
Pylinux

5
有否定感是什么意思time?从逻辑上讲,时差始终为正
mcont 2014年

4
您可以使用模数来获取秒数,我认为它更具可读性。var seconds = time % 60
JCM

106

另一个不错的解决方案:

function fancyTimeFormat(duration)
{   
    // Hours, minutes and seconds
    var hrs = ~~(duration / 3600);
    var mins = ~~((duration % 3600) / 60);
    var secs = ~~duration % 60;

    // Output like "1:01" or "4:03:59" or "123:03:59"
    var ret = "";

    if (hrs > 0) {
        ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
    }

    ret += "" + mins + ":" + (secs < 10 ? "0" : "");
    ret += "" + secs;
    return ret;
}

~~是的简写Math.floor,请参阅此链接以获取更多信息

在线尝试


14
是什么意思~~
mcont 2014年

9
这是基本的shorhand Math.floor,请参阅此链接
lapin 2015年

它的工作很好..... :)您可以像这样将值四舍五入hrs = hrs.toFixed(0); mins = mins.toFixed(0); secs = secs.toFixed(0);
阿卜杜勒·哈利克

1
感谢您的解决方案!我time = math.round(time)在第一行添加了四舍五入的时间。
fotoflo

这是更正确的解决方案。如上所述,此页面上投票数最多的解决方案将2秒60秒显示为180秒。
SongBox

71

对于希望使用快速简单且简短的解决方案将秒格式化为的人们M:SS

function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}

完成..
该函数接受一个Number(优选的)一个String(2转化“处罚”,这可以通过预先计算减半+在函数调用中的参数为s如下所示:fmtMSS(+strSeconds)),代表正整数秒s作为参数。

例子:

fmtMSS(    0 );  //   0:00
fmtMSS(   '8');  //   0:08
fmtMSS(    9 );  //   0:09
fmtMSS(  '10');  //   0:10
fmtMSS(   59 );  //   0:59
fmtMSS( +'60');  //   1:00
fmtMSS(   69 );  //   1:09
fmtMSS( 3599 );  //  59:59
fmtMSS('3600');  //  60:00
fmtMSS('3661');  //  61:01
fmtMSS( 7425 );  // 123:45

分解:

function fmtMSS(s){   // accepts seconds as Number or String. Returns m:ss
  return( s -         // take value s and subtract (will try to convert String to Number)
          ( s %= 60 ) // the new value of s, now holding the remainder of s divided by 60 
                      // (will also try to convert String to Number)
        ) / 60 + (    // and divide the resulting Number by 60 
                      // (can never result in a fractional value = no need for rounding)
                      // to which we concatenate a String (converts the Number to String)
                      // who's reference is chosen by the conditional operator:
          9 < s       // if    seconds is larger than 9
          ? ':'       // then  we don't need to prepend a zero
          : ':0'      // else  we do need to prepend a zero
        ) + s ;       // and we add Number s to the string (converting it to String as well)
}

注意:可以通过(0>s?(s=-s,'-'):'')+在返回表达式前添加负范围(实际上(0>s?(s=-s,'-'):0)+也可以)。


我建议添加Math.floor(s)到最后一行以获得更清晰的结果。反正工作很好,谢谢!
迭戈·福特斯

@PossessWithin:不,你要不要 “Math.floor(S)添加到最后一行”出于多种原因(故障-摘录的),最重要的,因为这将引入一个错误的之间的值9,并10没有进一步的修改; 例如,如果输入,69.25则输出将1:9改为1:09!此功能(我明确为其指定了整数秒)旨在并精心设计为高性能的运算工具/“引擎”(尺寸不适合忍者使用),因此,我认为此功能不适合通过不必要的验证来负担该引擎/ cleanup / filtering ...
GitaarLAB

...工作(如NaN+/-Infinity等)和舍入选项应该由程序员来完成,先调用函数,根据具体需要和可能的输入值,应用程序可能会遇到来!自然地,如果您对领域的期望输入值的知识表明您的特定用例几乎总是接收浮点值,并且性能测试表明您的应用程序是免费的,则可以对其进行修补。如果您只想修补正值的
底线,则

...修改(9<s?':':':0')(10>s?':0':':')(添加6个真实路径中的5个真实路径中添加1个字符,但“牺牲” 5个)或(10<=s?':':':0')(添加6个真实路径中的5个中添加2个字符,但保持5个真实路径)。于是我劝到最后沿变化+s+(s|0) 代替 Math.floor(s),以不破坏的美丽不是需要以决心和电话Math.floor ,同时仍然在正常运行整个 53bit +/-MAX_SAFE_INTEGER范围“只是” 32位(无符号)或31bit,而不是(签字)范围内!请注意,ABS(s)磁极保证小于60,因此已签名...
GitaarLAB

...按位签名或是安全的。还要注意的是,这种特殊的修改没有使剩余的秒数变小,这会使函数输出的分数秒数没有尾随零。但是,您通常也需要处理3个以上的非零数字。最后,与可选的负范围前缀代码结合使用时,此特殊修改将有效地截断秒数(而不是对秒进行平整)。PS: PFFT, whoever came up with just 512 char limit for any meaningful comment should be...
GitaarLAB

21

您还可以使用本机Date对象:

var date = new Date(null);
date.setSeconds(timeInSeconds);

// retrieve time ignoring the browser timezone - returns hh:mm:ss
var utc = date.toUTCString();
// negative start index in substr does not work in IE 8 and earlier
var time = utc.substr(utc.indexOf(':') - 2, 8)

// retrieve each value individually - returns h:m:s
var time = date.getUTCHours() + ':' + date.getUTCMinutes() + ':' +  date.getUTCSeconds();

// does not work in IE8 and below - returns hh:mm:ss
var time = date.toISOString().substr(11, 8);

// not recommended - only if seconds number includes timezone difference
var time = date.toTimeString().substr(0, 8);

当然,此解决方案仅适用于timeInSeconds少于24小时;)


1
没想到让Date对象处理格式。灵活性
较差

我用25秒尝试了一下,它返回了01:00:25,相当于1小时25秒。
timstermatic

是的,可能是因为您所在的时区。我已经更新了解决方案来处理这种情况。
hamczu

date也可以构建为var date = new Date(timeInSeconds * 1000)
NunoAndré17年

20

2019年最佳变种

格式 hh:mm:ss

console.log(display(60 * 60 * 2.5 + 25)) // 2.5 hours + 25 seconds

function display (seconds) {
  const format = val => `0${Math.floor(val)}`.slice(-2)
  const hours = seconds / 3600
  const minutes = (seconds % 3600) / 60

  return [hours, minutes, seconds % 60].map(format).join(':')
}


嗯,seconds是常量。您不能重新分配它。
ronapelbaum

@ronapelbaum这种说法,不是恒定的,我不明白你的意思
ИльяЗеленько

@ronapelbaum如果您指定秒而不是将秒作为必须使用的参数let,例如 function display (state) { let seconds = state.seconds; ... },那可能是您的错误出处?
retrovertigo

函数参数应视为const。使用时,%=您将重新分配此参数。只需使用seconds%60
ronapelbaum

16
function secondsToMinutes(time){
    return Math.floor(time / 60)+':'+Math.floor(time % 60);
}

3
可以通过零填充秒数来改进: function secondsToMinutes(time){ return Math.floor(0 / 60)+':'+('0'+Math.floor(0 % 60)).slice(-2); }
Kus

真好!谢谢@Kus。只是你可能要更换这两个0与S time,我是正确的吗?
mikey

2
@mikey哎呀!是的function secondsToMinutes(time){ return Math.floor(time / 60) + ':' + ('0' + Math.floor(time % 60)).slice(-2) }
Kus

12

要添加前导零,我将这样做:

var minutes = "0" + Math.floor(time / 60);
var seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);

好又短


9

使用ES6清洁一根衬板


const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);

6

一个班轮(不工作几个小时):

 function sectostr(time) {
    return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
 }

4

秒:h:mm:ss

var hours = Math.floor(time / 3600);
time -= hours * 3600;

var minutes = Math.floor(time / 60);
time -= minutes * 60;

var seconds = parseInt(time % 60, 10);

console.log(hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds));

minutes < 10 ? '0' + minutes : minutes假设只具备基本的js知识,有人可以为我解释吗?
Zediiiii

如果分钟是个位数(<10),则前加零。
kayz1

有帮助!我没有意识到“?” 是js中的三元运算符。
Zediiiii

4

以下功能将帮助您获取天,小时,分钟,秒

toDDHHMMSS(inputSeconds){
        const Days = Math.floor( inputSeconds / (60 * 60 * 24) );
        const Hour = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60));
        const Minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60 );
        const Seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60 );
        let ddhhmmss  = '';
        if (Days > 0){
            ddhhmmss += Days + ' Day ';
        }
        if (Hour > 0){
            ddhhmmss += Hour + ' Hour ';
        }

        if (Minutes > 0){
            ddhhmmss += Minutes + ' Minutes ';
        }

        if (Seconds > 0){
            ddhhmmss += Seconds + ' Seconds ';
        }
        return ddhhmmss;
    }
alert( toDDHHMMSS(2000));

我喜欢这一个。我改if (Days > 0){ ddhhmmss += Days + ' Day '; }if (Days > 0) {ddhhmmss += Days === 1 ? Days + ' Day ' : Days + ' Days '};1 Day2 Days3 Days等可以为其他人做过类似的。
Ste

4

毕竟,还有另一个简单的解决方案:

const time = new Date(null);
time.setSeconds(7530);
console.log(time.getHours(), time.getMinutes(), time.getSeconds());

1
应该在应该使用time.setSeconds(1);return 1 0 1时使用0 0 1
Ste

3

另一个但更优雅的解决方案如下:

/**
 * Convert number secs to display time
 *
 * 65 input becomes 01:05.
 *
 * @param Number inputSeconds Seconds input.
 */
export const toMMSS = inputSeconds => {
    const secs = parseInt( inputSeconds, 10 );
    let minutes = Math.floor( secs / 60 );
    let seconds = secs - minutes * 60;

    if ( 10 > minutes ) {
        minutes = '0' + minutes;
    }
    if ( 10 > seconds ) {
        seconds = '0' + seconds;
    }

    // Return display.
    return minutes + ':' + seconds;
};

2

对于加零,我真的不认为需要使用其他完整功能,例如

var mins=Math.floor(StrTime/60);
var secs=StrTime-mins * 60;
var hrs=Math.floor(StrTime / 3600);
RoundTime.innerHTML=(hrs>9?hrs:"0"+hrs) + ":" + (mins>9?mins:"0"+mins) + ":" + (secs>9?secs:"0"+secs);

这就是为什么我们首先要有条件语句的原因。

(条件?如果为true:如果为false),因此如果示例秒数大于9,而不仅仅是显示秒数,则在其前面添加字符串0。


2

试试这个:将Second转换为HOURS,MIN和SEC。

function convertTime(sec) {
    var hours = Math.floor(sec/3600);
    (hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
    var min = Math.floor(sec/60);
    (min >= 1) ? sec = sec - (min*60) : min = '00';
    (sec < 1) ? sec='00' : void 0;

    (min.toString().length == 1) ? min = '0'+min : void 0;    
    (sec.toString().length == 1) ? sec = '0'+sec : void 0;    

    return hours+':'+min+':'+sec;
}

2

var seconds = 60;
var measuredTime = new Date(null);
measuredTime.setSeconds(seconds); // specify value of SECONDS
var Time = measuredTime.toISOString().substr(11, 8);
document.getElementById("id1").value = Time;
<div class="form-group">
  <label for="course" class="col-md-4">Time</label>
  <div class="col-md-8">
    <input type="text" class="form-control" id="id1" name="field">Min
  </div>
</div>



2

2020更新

使用基本数学和简单的javascript,只需几行代码即可完成。

示例-转换7735 secondsHH:MM:SS


数学:

计算用途:

  1. Math.floor()- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

Math.floor()函数返回小于或等于给定数字的最大整数。

  1. %算术运算符(Remainder)-https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder

当一个操作数除以第二个操作数时,余数运算符返回剩余的余数。它总是带有股息的迹象。

在下面查看代码。秒数除以3600小时数和余数,余数用于计算分钟数和秒数。

HOURS => 7735 / 3600 = 2 remainder 535

MINUTES => 535 / 60 = 8 remainder 55

SECONDS => 55


领先的ZEROS:

这里的许多答案都使用复杂的方法,以正确的方式显示小时,分钟和秒数,并以零开头4504以此类推。可以使用来完成padStart()。这适用于字符串,因此必须使用将数字转换为字符串toString()

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

padStart()方法用另一个字符串(如果需要,可以多次)填充当前字符串,直到结果字符串达到给定的长度为止。从当前字符串的开头开始应用填充。


码:

function secondsToTime(e){
    var h = Math.floor(e / 3600).toString().padStart(2,'0'),
        m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),
        s = Math.floor(e % 60).toString().padStart(2,'0');
    
    return h + ':' + m + ':' + s;
}

console.log(secondsToTime(7735));  //02:08:55

/*
secondsToTime(SECONDS) => HH:MM:SS 

secondsToTime(8)       => 00:00:08 
secondsToTime(68)      => 00:01:08
secondsToTime(1768)    => 00:29:28
secondsToTime(3600)    => 01:00:00
secondsToTime(5296)    => 01:28:16
secondsToTime(7735)    => 02:08:55
secondsToTime(45296)   => 12:34:56
secondsToTime(145296)  => 40:21:36
secondsToTime(1145296) => 318:08:16
*/


1

您已经完成了足够的代码来跟踪时间的分钟和秒部分。

您可以做的是将小时数因子添加到:

var hrd = time % (60 * 60 * 60);
var hours = Math.floor(hrd / 60);

var mind = hrd % 60;
var minutes = Math.floor(mind / 60);

var secd = mind % 60;
var seconds = Math.ceil(secd);

var moreminutes = minutes + hours * 60

这也将为您提供所需的东西。


我使用“时间”作为秒尝试了一下,但是没有用。例如,975秒装置HRD = 975,其手段小时16
Spedge

1

我在想一种更快的方法来完成此任务,这就是我想出的

var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}

如果要将“时间”转换为分钟和秒,例如:

// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1

1

把我的两分钱放在:

function convertSecondsToMinutesAndSeconds(seconds){
            var minutes;
            var seconds;
            minutes = Math.floor(seconds/60);
            seconds = seconds%60;

            return [minutes, seconds];
        }

所以这 :

var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101);

将具有以下输出:

[1,41];

然后,您可以像这样打印它:

console.log('TIME : ' +  minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds');

//TIME : 1 minutes, 41 seconds

1

strftime.js(strftime github)是最好的时间格式化库之一。它非常轻巧-30KB-并且有效。使用它,您可以在一行代码中轻松地将秒转换为时间,而这主要依赖于本机的Date类。

创建新的Date时,每个可选参数的位置如下:

new Date(year, month, day, hours, minutes, seconds, milliseconds);

因此,如果您初始化一个新的Date且所有参数都为零(直到秒),您将得到:

var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)

您可以看到150秒是2分钟30秒,如创建日期所示。然后使用strftime格式(“ MM:SS”使用“%M:%S”),它将输出您的分钟字符串。

var mm_ss_str = strftime("%M:%S", date);
=> "02:30"

在一行中,它看起来像:

var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"

加上这将使您可以基于秒数互换支持HH:MM:SS和MM:SS。例如:

# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"

# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"

当然,如果您希望时间字符串具有或多或少的语义,则可以简单地传递想要的strftime格式。

var format = 'Honey, you said you\'d be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"

希望这可以帮助。


1
export function TrainingTime(props) {
    const {train_time } = props;
    const hours = Math.floor(train_time/3600);
    const minutes = Math.floor((train_time-hours * 3600) / 60);
    const seconds = Math.floor((train_time%60));

    return `${hours} hrs  ${minutes} min  ${seconds} sec`;
}

2
欢迎使用堆栈溢出。正如@PhilRoggenbuck所建议的那样,进行解释会有所帮助。有关更多信息,请阅读stackoverflow.com/help/how-to-answer
Mikkel,

0

我建议另一种解决方案:

function formatTime(nbSeconds, hasHours) {
    var time = [],
        s = 1;
    var calc = nbSeconds;

    if (hasHours) {
        s = 3600;
        calc = calc / s;
        time.push(format(Math.floor(calc)));//hour
    }

    calc = ((calc - (time[time.length-1] || 0)) * s) / 60;
    time.push(format(Math.floor(calc)));//minute

    calc = (calc - (time[time.length-1])) * 60;
    time.push(format(Math.round(calc)));//second


    function format(n) {//it makes "0X"/"00"/"XX"
        return (("" + n) / 10).toFixed(1).replace(".", "");
    }

    //if (!hasHours) time.shift();//you can set only "min: sec"

    return time.join(":");
};
console.log(formatTime(3500));//58:20
console.log(formatTime(305));//05:05
console.log(formatTime(75609, true));//21:00:09
console.log(formatTime(0, true));//00:00:00


0

我知道它已经通过许多方式解决了。我需要After Effects脚本使用此功能,在该脚本中速度或名称空间污染不是问题。我把它放在这里给需要类似东西的人。我还编写了一些测试并且工作正常。所以这是代码:

Number.prototype.asTime = function () {
    var hour = Math.floor(this / 3600),
        min = Math.floor((this - hour * 3600) / 60),
        sec = this - hour * 3600 - min * 60,
        hourStr, minStr, secStr;
    if(hour){
        hourStr = hour.toString(),
        minStr = min < 9 ? "0" + min.toString() : min.toString();
        secStr = sec < 9 ? "0" + sec.toString() : sec.toString();
        return hourStr + ":" + minStr + ":" + secStr + "hrs";
    }
    if(min){
        minStr = min.toString();
        secStr = sec < 9 ? "0" + sec.toString() : sec.toString();
        return  minStr + ":" + secStr + "min";
    }
    return sec.toString() + "sec";
}
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.