Javascript 如何在javascript中将秒转换为分钟和小时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37096367/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:54:36  来源:igfitidea点击:

How to convert seconds to minutes and hours in javascript

javascript

提问by ALSD Minecraft

I have a count of seconds stored in variable seconds. I want to convert for example 1439 seconds to 23 minutes and 59 seconds. And if the time is greater than 1 hour (for example 9432 seconds), to 2 hours, 37 minutes and 12 seconds.

我有一个存储在变量中的秒数seconds。我想将例如 1439 秒转换为 23 分 59 秒。而如果时间大于 1 小时(例如 9432 秒),则为 2 小时 37 分 12 秒。

How can I achieve this?

我怎样才能做到这一点?

I'm thinking of:

我在想:

var sec, min, hour;

if(seconds<3600){
    var a = Math.floor(seconds/60); //minutes
    var b = seconds%60; //seconds

    if (b!=1){
        sec = "seconds";
    }else{
        sec = "second";
    }

    if(a!=1){
        min = "minutes";
    }else{
        min = "minute";
    }

    $('span').text("You have played "+a+" "+min+" and "+b+" "+sec+".");
}else{
        var a = Math.floor(seconds/3600); //hours
    var x = seconds%3600;
    var b = Math.floor(x/60); //minutes
    var c = seconds%60; //seconds

     if (c!=1){
        sec = "seconds";
    }else{
        sec = "second";
    }

    if(b!=1){
        min = "minutes";
    }else{
        min = "minute";
    }

    if(c!=1){
        hour = "hours";
    }else{
        hour = "hour";
    }

    $('span').text("You have played "+a+" "+hour+", "+b+" "+min+" and "+c+" "+sec+".");
}

But that's a lot of code, and it has to be calculated each second. How can I shrink this up?

但那是很多代码,而且必须每秒计算一次。我怎样才能缩小这个?

回答by Wilson Lee

I think you would find this solutionvery helpful.

我想你会发现这个解决方案非常有帮助。

You modify the display format to fit your needs with something like this -

您可以使用以下内容修改显示格式以满足您的需求 -

function secondsToHms(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
    var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
    var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
    return hDisplay + mDisplay + sDisplay; 
}

回答by R4nc1d

You can try this, i have used this successfully in the past You should be able to add the minutes and seconds on easily

你可以试试这个,我过去成功地使用过你应该能够轻松添加分钟和秒

function secondsToTime(secs)
{
    var hours = Math.floor(secs / (60 * 60));

    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);

    var obj = {
        "h": hours,
        "m": minutes,
        "s": seconds
    };
    return obj;
}

Fiddle

小提琴

You can change the object to

您可以将对象更改为

var obj = {
        "h": hours + " hours",
        "m": minutes + " minutes",
        "s": seconds + " seconds"
    };

回答by Brian

A low fat way to do this is:

一个低脂肪的方法是:

function seconds_to_days_hours_mins_secs_str(seconds)
{ // day, h, m and s
  var days     = Math.floor(seconds / (24*60*60));
      seconds -= days    * (24*60*60);
  var hours    = Math.floor(seconds / (60*60));
      seconds -= hours   * (60*60);
  var minutes  = Math.floor(seconds / (60));
      seconds -= minutes * (60);
  return ((0<days)?(days+" day, "):"")+hours+"h, "+minutes+"m and "+seconds+"s";
}

Thus

因此

> seconds_to_days_hours_mins_secs_str(9432+60*60*24)
'1 days, 2h, 37m and 12s'

This is easy to understand and extend as needed.

这很容易理解并根据需要进行扩展。

回答by pkerckhove

I'm probably a bit late but you can achieve this kind of things using

我可能有点晚了,但你可以使用

https://momentjs.com/

https://momentjs.com/

myVar = moment(myVar).format('HH:mm');

myVar = moment(myVar).format('HH:mm');

moment provides A LOT of format for hours / dates etc.

moment 为小时/日期等提供了很多格式。

回答by David

I found Wilson Lee's and Brian's code super useful! Here is how I adapted their code:

我发现 Wilson Lee 和 Brian 的代码非常有用!这是我如何调整他们的代码:

function formatTime(serverTimeinSeconds, elementId)
{ /* This converts seconds into days, hours, minutes and seconds timestring.
     Requires JQuery if elementId argument is provided */
  seconds = Math.floor(Number(serverTimeinSeconds));
  days = Math.floor(seconds / (24*60*60));
  seconds -= Math.floor(days    * (24*60*60));
  hours    = Math.floor(seconds / (60*60));
  seconds -= Math.floor(hours   * (60*60));
  minutes  = Math.floor(seconds / (60));
  seconds -= Math.floor(minutes * (60));

  dDisplay = days > 0 ? days + (days == 1 ? ' day, ' : ' days, ') : '';
  hDisplay = hours > 0 ? hours + (hours == 1 ? ' hour, ' : ' hours, ') : '';
  mDisplay = minutes > 0 ? minutes + (minutes == 1 ? ' minute, ' : ' minutes, ') : '';
  sDisplay = seconds > 0 ? seconds + (seconds == 1 ? ' second' : ' seconds') : '';

  if (elementId != null) {
    if (serverTimeinSeconds < 60) {
        $(elementId).css('font-size', '15px');
        $(elementId).html(sDisplay);
    }
    if (serverTimeinSeconds >= 60 && serverTimeinSeconds < 3600) {
        $(elementId).css('font-size', '15px');
        $(elementId).html(mDisplay + sDisplay);
    }
    if (serverTimeinSeconds >= 3600 && serverTimeinSeconds < 86400) {
        $(elementId).css('font-size', '12px');
        $(elementId).html(hDisplay + mDisplay + sDisplay);
    }
    if (serverTimeinSeconds >= 86400 && serverTimeinSeconds !== Infinity) {
        $(elementId).css('font-size', '8px');
        $(elementId).html(dDisplay + hDisplay + mDisplay + sDisplay);
    }
  }
  return dDisplay + hDisplay + mDisplay + sDisplay;
}

回答by Sushil

Try this, Convert SEC to H:M:S.

试试这个,将 SEC 转换为 H:M:S。

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

回答by tkleiven

@pkerckhove has already mentioned momentas a great library to work with dates and times, and you can also use momentto directly format the seconds into OP's desired format, i.e.:

@pkerckhove 已经提到moment了一个很棒的库来处理日期和时间,您还可以使用moment直接将秒格式化为 OP 所需的格式,即:

import moment from 'moment'

const myVar = 1439
console.log(
    moment.unix(myVar).utc().format('H [hours,] m [minutes and] s [seconds]')
)

Will result in: 0 hours, 23 minutes and 59 secondsand,

将导致:0 hours, 23 minutes and 59 seconds并且,

import moment from 'moment'

const myVar = 9432
console.log(
    moment.unix(myVar).utc().format('H [hours,] m [minutes and] s [seconds]')
)

Will result in: 2 hours, 37 minutes and 12 seconds

会导致: 2 hours, 37 minutes and 12 seconds

回答by Mukesh Kumar Bijarniya

Convert to H:M

转换为 H:M

Number(moment.duration(Number(37320), 'seconds').hours()+'.'+moment.duration(Number(37320),'seconds').minutes())