Javascript秒到分钟和秒

Jam*_*ore 151 javascript

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

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

var secd = mind % 60;
var seconds = Math.ceil(secd);
Run Code Online (Sandbox Code Playgroud)

但是,当我达到1小时或3600秒时,它返回0分0秒.如何避免这种情况,以便返回所有分钟?

谢谢

Gum*_*mbo 304

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

var minutes = Math.floor(time / 60);
Run Code Online (Sandbox Code Playgroud)

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

var seconds = time - minutes * 60;
Run Code Online (Sandbox Code Playgroud)

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

var hours = Math.floor(time / 3600);
time = time - hours * 3600;
Run Code Online (Sandbox Code Playgroud)

然后计算完整的分钟数和剩余的秒数.

奖金:

使用以下代码来打印时间(由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);
Run Code Online (Sandbox Code Playgroud)

  • 通过执行'var seconds = time%60'来获得剩余秒数会更清晰一些. (50认同)
  • @Radio使用`function str_pad_left(string,pad,length){return(new Array(length + 1).join(pad)+ string).slice(-length);添加前导零.} var finalTime = str_pad_left(分钟,'0',2)+':'+ str_pad_left(秒,'0',2);` (10认同)
  • 有消极的"时间"的感觉是什么?从逻辑上讲,时差始终是正的 (5认同)
  • 您可以使用模数来获得秒数,在我看来它更具可读性.``var seconds = time%60`` (4认同)
  • 您可以使用内置的 JavaScript `string.padStart()` 方法用零填充单个数字。 (2认同)

Vis*_*hal 93

另一个奇特的解决方案

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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 什么是`~~`的意思? (12认同)
  • 它是`Math.floor`的基本版,见[this link](http://rocha.la/JavaScript-bitwise-operators-in-practice). (8认同)
  • 该解决方案也适用于"时间"的负值 (3认同)
  • 感谢这个解决方案!我在第一行添加了 `time = math.round(time)` 来给我四舍五入的秒数。 (2认同)

Git*_*LAB 67

对于那些希望通过快速简单而简短的解决方案将人们设置为M:SS:

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

完成..
该函数接受一个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
Run Code Online (Sandbox Code Playgroud)

分解:

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)
}
Run Code Online (Sandbox Code Playgroud)

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


Jak*_*uda 23

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. %算术运算符(余数) - 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){
    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;
    //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
*/
Run Code Online (Sandbox Code Playgroud)


ham*_*czu 18

您还可以使用本机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);
Run Code Online (Sandbox Code Playgroud)

当然这个解决方案仅适用于不到24小时的timeInSeconds;)


El0*_*din 14

function secondsToMinutes(time){
    return Math.floor(time / 60)+':'+Math.floor(time % 60);
}
Run Code Online (Sandbox Code Playgroud)

  • 这可以通过零填充秒来改进:```function secondsToMinutes(time){return Math.floor(0/60)+':'+('0'+ Math.floor(0%60)).slice( -2); }``` (3认同)
  • @mikey哎呀!是的,`function secondsToMinutes(time){return Math.floor(time/60)+':'+('0'+ Math.floor(time%60)).slice(-2)}` (2认同)

Иль*_*ько 14

2018年最佳变种

格式 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(':')
}
Run Code Online (Sandbox Code Playgroud)


Ids*_*sma 11

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

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

好又短


Gil*_*ain 10

时刻.js

如果您使用的是Moment.js,那么您可以使用内置Duration对象

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

const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25
Run Code Online (Sandbox Code Playgroud)


Sam*_*gan 6

使用ES6清洁一根衬板


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

Run Code Online (Sandbox Code Playgroud)


Dir*_*Doc 6

我发现的最简洁的方法可以在一行中完成:

let timeString = `${timeInSeconds/60|0}:${timeInSeconds%60}`
Run Code Online (Sandbox Code Playgroud)

解释

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

timeInSeconds/60|0
将秒数转换为分钟数 ( /60)。这给出了一个有理数。从这里它被截断使用按位 OR ( |0)

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


小时

此方法可以扩展为包括这样的小时:

let timeString = `${timeInSeconds/60/60|0}:${timeInSeconds/60%60|0}:${timeInSeconds%60}`
Run Code Online (Sandbox Code Playgroud)

重复此过程,您甚至可以包括天数。


kay*_*yz1 5

秒到 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));
Run Code Online (Sandbox Code Playgroud)


小智 5

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

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


use*_*839 5

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

const time = new Date(null);
time.setSeconds(7530);
console.log(time.getHours(), time.getMinutes(), time.getSeconds());
Run Code Online (Sandbox Code Playgroud)