Answers:
要获得完整的分钟数,请用总秒数除以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);
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);
time
。例如,如果您输入-1秒,则返回-1分59秒……
time
?从逻辑上讲,时差始终为正
var seconds = time % 60
另一个不错的解决方案:
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
,请参阅此链接以获取更多信息
~~
?
Math.floor
,请参阅此链接。
time = math.round(time)
在第一行添加了四舍五入的时间。
对于希望使用快速简单且简短的解决方案将秒格式化为的人们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)
到最后一行以获得更清晰的结果。反正工作很好,谢谢!
9
,并10
没有进一步的修改; 例如,如果输入,69.25
则输出将1:9
改为1:09
!此功能(我明确为其指定了整数秒)旨在并精心设计为高性能的运算工具/“引擎”(尺寸不适合忍者使用),因此,我认为此功能不适合通过不必要的验证来负担该引擎/ cleanup / filtering ...
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,因此已签名...
PS: PFFT, whoever came up with just 512 char limit for any meaningful comment should be...
您还可以使用本机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小时;)
date
也可以构建为var date = new Date(timeInSeconds * 1000)
格式 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
是常量。您不能重新分配它。
let
,例如 function display (state) { let seconds = state.seconds; ... }
,那可能是您的错误出处?
%=
您将重新分配此参数。只需使用seconds%60
function secondsToMinutes(time){
return Math.floor(time / 60)+':'+Math.floor(time % 60);
}
function secondsToMinutes(time){ return Math.floor(0 / 60)+':'+('0'+Math.floor(0 % 60)).slice(-2); }
0
与S time
,我是正确的吗?
function secondsToMinutes(time){ return Math.floor(time / 60) + ':' + ('0' + Math.floor(time % 60)).slice(-2) }
const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);
秒: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知识,有人可以为我解释吗?
以下功能将帮助您获取天,小时,分钟,秒
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 Day
,2 Days
,3 Days
等可以为其他人做过类似的。
另一个但更优雅的解决方案如下:
/**
* 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;
};
对于加零,我真的不认为需要使用其他完整功能,例如
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。
试试这个:将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;
}
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>
如果您正在使用Moment.js,则可以使用内置Duration
对象
const duration = moment.duration(4825, 'seconds');
const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25
使用基本数学和简单的javascript,只需几行代码即可完成。
示例-转换7735 seconds
为HH:MM:SS
。
计算用途:
Math.floor()
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor 该
Math.floor()
函数返回小于或等于给定数字的最大整数。
%
算术运算符(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
这里的许多答案都使用复杂的方法,以正确的方式显示小时,分钟和秒数,并以零开头45
,04
以此类推。可以使用来完成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
*/
您已经完成了足够的代码来跟踪时间的分钟和秒部分。
您可以做的是将小时数因子添加到:
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
这也将为您提供所需的东西。
我在想一种更快的方法来完成此任务,这就是我想出的
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
把我的两分钱放在:
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
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!"
希望这可以帮助。
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`;
}
我建议另一种解决方案:
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
我知道它已经通过许多方式解决了。我需要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";
}