Javascript秒到分和秒

这是一个常见的问题,但我不知道如何解决它。下面的代码可以正常工作。

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

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

然而,当我到达1小时或3600秒时,它返回0分和0秒。我如何避免这种情况,让它返回所有的分钟?

346848 次浏览

要得到完整的分钟数,将总秒数除以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);

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

你可以把时间因素加进去:

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

你也可以使用本机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);

当然,这个解决方案只适用于小于24小时的timeInSeconds;)

另一个奇妙的解决方案:

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的缩写,更多信息请参见这个链接

Try online .

我在想一个更快的方法来完成这件事,这就是我想到的

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

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

对于加0,我真的不认为需要有一个完整的其他函数,你可以简单地使用例如

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

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

(条件?如果instance seconds大于9,则只显示seconds否则在它前面添加字符串0。

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

const secondsToMinSecPadded = time => {
const minutes = "0" + Math.floor(time / 60);
const seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);
};




console.log(secondsToMinSecPadded(241));

很好,很短

对于那些希望将秒格式化为M:SS的快速简单的解决方案的人:

function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
< br > < p >做. . 该函数接受要么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)+也可以)。

一句话(不适合几个小时):

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

说说我的意见:

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
function secondsToMinutes(time){
return Math.floor(time / 60)+':'+Math.floor(time % 60);
}

试试这个:
将秒转换为小时,分钟和秒

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

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

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

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

因此,如果你初始化一个new Date,所有参数都为0,直到秒,你会得到:

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格式("%M:%S"对于"MM:SS"),它将输出您的分钟字符串。

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

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

/**
* 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;
};
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`;
}

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>

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(':')
}

下面的函数将帮助您获得日,小时,分钟,秒

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

使用ES6清洁一个衬垫


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


在这一切之后,还有一个简单的解决方案:

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

Moment.js

如果你正在使用Moment.js .js,那么你可以使用内置的Duration对象

const duration = moment.duration(4825, 'seconds');


const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25

2020年更新

使用基本的数学和简单的javascript,这可以在几行代码中完成。

7735 seconds转换为HH:MM:SS


数学:

计算使用:

  1. __abc0 - __abc1

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

  1. %算术运算符(余数)- 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


前导零:

这里的许多答案使用复杂的方法来显示小时数、分钟数和秒数,以一种正确的方式引导零——4504等。这可以使用padStart()来完成。这适用于字符串,因此必须使用toString()将数字转换为字符串。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

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


代码:

function secondsToTime(e){
const 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;
//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
*/

我发现的最简洁的方法只用一行就可以完成:

let timeString = `${timeInSeconds/60|0}:${timeInSeconds%60}`

解释

`${...}`
模板文字。允许表达式从字符串本身转换为字符串。
注意: IE不兼容。

timeInSeconds/60|0
以秒为单位并转换为分钟(/60)。这给出了一个有理数。从这里开始使用按位或 (|0)来截断它

timeInSeconds%60
剩余(模)。给出变量的余数除以60。


小时

这种方法可以扩展到包括这样的时间:

let timeString = `${timeInSeconds/60/60|0}:${timeInSeconds/60%60|0}:${timeInSeconds%60}`

重复这个过程,你甚至可以加上天。

我更喜欢将Millisecond视为自己的单元,而不是其他东西的子单元。从这个意义上说,它的值是0-999,所以你会想要填充3而不是2,就像我在其他答案中看到的那样。下面是一个实现:

function format(n) {
let mil_s = String(n % 1000).padStart(3, '0');
n = Math.trunc(n / 1000);
let sec_s = String(n % 60).padStart(2, '0');
n = Math.trunc(n / 60);
return String(n) + ' m ' + sec_s + ' s ' + mil_s + ' ms';
}


console.log(format(241));

https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/String/padStart

  function formatSeconds(s: number) {
let minutes = ~~(s / 60);
let seconds = ~~(s % 60);
return minutes + ':' + seconds;
}

Day.js

如果你使用day.js,试试这个。

const dayjs = require('dayjs')
const duration = require('dayjs/plugin/duration')
dayjs.extend(duration)


const time = dayjs.duration(100, 'seconds')


time.seconds() // 40
time.minutes() // 1
time.format('mm:ss') // 01:40

1 -使用%获取除法的其余部分。现在你有了一分钟还不够完整的几秒钟 2 -从总数中减去步骤1中获得的秒数。现在你有分钟

例如,让我们假设你有700秒:

seconds = 700%60); //40 seconds
minutes = (700 - (700%60))/60; //11
//11:40

这是一个ES6版本的秒到分钟和秒的转换,带有填充(00:00格式)。它只接受整数值的秒和~~(x)是速记地板操作。

const padTime = n => ("" + n).padStart(2, 0);
const secondsToMinSec = time =>
`${padTime(~~(time / 60))}:${padTime(time - ~~(time / 60) * 60)}`
;


for (let i = 0; i < 10; i++) {
const seconds = ~~(Math.random() * 300);
console.log(seconds, secondsToMinSec(seconds));
}

如果你需要工作的结果很容易,这是我使用:

function seconds2hms(seconds, milliseconds) {
if(milliseconds) {
seconds = Math.floor(seconds/1000);
}
return {h:~~(seconds / 3600),m:~~((seconds % 3600) / 60),s:~~seconds % 60}

(使用Vishal的代码)