Javascript 秒到分钟和秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3733227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript seconds to minutes and seconds
提问by James Moore
This is a common problem but I'm not sure how to solve it. The code below works fine.
这是一个常见问题,但我不确定如何解决。下面的代码工作正常。
var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
However, when I get to 1 hour or 3600 seconds it returns 0 minutes and 0 seconds. How can I avoid this so it returns all the minutes?
但是,当我达到 1 小时或 3600 秒时,它返回 0 分 0 秒。我怎样才能避免这种情况,以便它返回所有分钟?
Thanks
谢谢
回答by Gumbo
To get the number of full minutes, divide the number of total seconds by 60 (60 seconds/minute):
要获得完整的分钟数,请将总秒数除以 60(60 秒/分钟):
var minutes = Math.floor(time / 60);
And to get the remaining seconds, multiply the full minutes with 60 and subtract from the total seconds:
要获得剩余的秒数,请将完整分钟数乘以 60,然后从总秒数中减去:
var seconds = time - minutes * 60;
Now if you also want to get the full hours too, divide the number of total seconds by 3600 (60 minutes/hour · 60 seconds/minute) first, then calculate the remaining seconds:
现在,如果您还想获得完整的小时数,请先将总秒数除以 3600(60 分钟/小时·60 秒/分钟),然后计算剩余秒数:
var hours = Math.floor(time / 3600);
time = time - hours * 3600;
Then you calculate the full minutes and remaining seconds.
然后计算完整的分钟数和剩余的秒数。
Bonus:
奖金:
Use the following code to pretty-print the time (suggested by Dru)
使用以下代码漂亮地打印时间(由 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);
回答by Vishal
Another fancy solution:
另一个奇特的解决方案:
function fancyTimeFormat(time)
{
// Hours, minutes and seconds
var hrs = ~~(time / 3600);
var mins = ~~((time % 3600) / 60);
var secs = ~~time % 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;
}
~~
is a shorthand for Math.floor
, see this linkfor more info
~~
是 的简写Math.floor
,请参阅此链接以获取更多信息
回答by GitaarLAB
For people dropping in hoping for a quick simple and thus short solution to format seconds into M:SS
:
对于希望快速简单且简短的解决方案来将秒格式化为M:SS
:
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
done..
The function accepts eithera Number
(preferred) ora String
(2 conversion 'penalties' which you can halve by prepending +
in the function call's argument for s
as in: fmtMSS(+strSeconds)
), representing positive integer seconds s
as argument.
完成..
该函数接受任一个Number
(优选的)或一个String
(2转化“处罚”,这可以通过预先计算减半+
在函数调用中的参数为s
如下所示:fmtMSS(+strSeconds)
),代表正整数秒s
作为参数。
Examples:
例子:
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
Breakdown:
分解:
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)
}
Note: Negative range could be added by prepending (0>s?(s=-s,'-'):'')+
to the return expression (actually, (0>s?(s=-s,'-'):0)+
would work as well).
注意:可以通过(0>s?(s=-s,'-'):'')+
在返回表达式前面添加负范围(实际上(0>s?(s=-s,'-'):0)+
也可以)。
回答by hamczu
You can also use native Date object:
您还可以使用本机 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);
Of course this solution works only for timeInSeconds less than 24 hours ;)
当然,此解决方案仅适用于不到 24 小时的 timeInSeconds ;)
回答by Илья Зеленько
2019 best variant
2019 最佳变体
Format hh:mm:ss
格式 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(':')
}
回答by El0din
function secondsToMinutes(time){
return Math.floor(time / 60)+':'+Math.floor(time % 60);
}
回答by Ids Klijnsma
To add leading zeros, I would just do:
要添加前导零,我会这样做:
var minutes = "0" + Math.floor(time / 60);
var seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);
Nice and short
好看又短
回答by Sam Logan
Clean one liner using ES6
使用 ES6 清洁一个衬垫
const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);
回答by Dillon
A one liner (doesnt work with hours):
一个班轮(不工作小时):
function sectostr(time) {
return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
}
回答by kayz1
Seconds to h:mm:ss
秒到 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));