Javascript 将秒转换为天、小时、分钟和秒

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

Convert seconds to days, hours, minutes and seconds

javascript

提问by Danielle Rose Mabunga

I have a Javascript timing event with an infinite loop with a stop button.

我有一个带有停止按钮的无限循环的 Javascript 计时事件。

It will display numbers when start button is click.Now I want this numbers converted to something like 4 hours, 3 minutes , 50 seconds

单击开始按钮时它将显示数字。现在我希望将这些数字转换为 4 小时 3 分钟 50 秒

var c = 0;
var t;
var timer_is_on = 0;

function timedCount() {
  document.getElementById('txt').value = c;
  c = c + 1;
  t = setTimeout(function() {
    timedCount()
  }, 1000);
}

function doTimer() {
  if (!timer_is_on) {
    timer_is_on = 1;
    timedCount();
  }
}

function stopCount() {
  clearTimeout(t);
  timer_is_on = 0;

}

$(".start").on("click", function() {
  //var start = $.now();
  //alert(start);
  //console.log(start);
  doTimer();
  $(".end").show();
  $(".hide_div").show();
});
$(".end").on("click", function() {
  stopCount();
});
.hide_div {
  display: none;
}

.end {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="start">Start</p>
<p class="end">End</p>
<p class="hide_div">
  <input type="text" id="txt" />//display numbers eg 12345
</p>

How to convert numbers like 123456 to 1 day, 4 hours, 40 min, 45 seconds?

如何将 123456 之类的数字转换为 1 天 4 小时 40 分 45 秒?

回答by Andris

I suggest doing this way!:

我建议这样做!:

function secondsToDhms(seconds) {
seconds = Number(seconds);
var d = Math.floor(seconds / (3600*24));
var h = Math.floor(seconds % (3600*24) / 3600);
var m = Math.floor(seconds % 3600 / 60);
var s = Math.floor(seconds % 60);

var dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : "";
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 dDisplay + hDisplay + mDisplay + sDisplay;
}

回答by Niklesh Raut

Use Mathlike this way, Second param in parseIntis for base, which is optional

Math像这样使用,第二个参数parseInt是基数,这是可选的

var seconds = parseInt(123456, 10);

var days = Math.floor(seconds / (3600*24));
seconds  -= days*3600*24;
var hrs   = Math.floor(seconds / 3600);
seconds  -= hrs*3600;
var mnts = Math.floor(seconds / 60);
seconds  -= mnts*60;
console.log(days+" days, "+hrs+" Hrs, "+mnts+" Minutes, "+seconds+" Seconds");

Your given seconds 123456would be 1 days, 10 Hrs, 17 Minutes, 36 Secondsnot 1 days, 4 Hrs, 40 Minutes, 45 Seconds

你给秒1234561 days, 10 Hrs, 17 Minutes, 36 Seconds1 days, 4 Hrs, 40 Minutes, 45 Seconds

回答by stopsopa

// countdown(3546544) -> 41d 1h 9m 4s
// countdown(436654) -> 5d 1h 17m 34s
// countdown(3601) -> 1h 0m 1s
// countdown(121) -> 2m 1s
const countdown = (function () {
    const pad = t => {
        return (t + '').length < 2 ? pad('0' + t + '') : t ;
    }
    return s => {

        const d = Math.floor(s / (3600 * 24));

        s  -= d * 3600 * 24;

        const h   = Math.floor(s / 3600);

        s  -= h * 3600;

        const m = Math.floor(s / 60);

        s  -= m * 60;

        const tmp = [];

        (d) && tmp.push(d + 'd');

        (d || h) && tmp.push(h + 'h');

        (d || h || m) && tmp.push(m + 'm');

        tmp.push(s + 's');

        return tmp.join(' ');
    }
}());

回答by timothyzhang

My solution with map() and reduce():

我的 map() 和 reduce() 解决方案:

const intervalToLevels = (interval, levels) => {
  const cbFun = (d, c) => {
    let bb = d[1] % c[0],
      aa = (d[1] - bb) / c[0];
    aa = aa > 0 ? aa + c[1] : '';

    return [d[0] + aa, bb];
  };

  let rslt = levels.scale.map((d, i, a) => a.slice(i).reduce((d, c) => d * c))
    .map((d, i) => ([d, levels.units[i]]))
    .reduce(cbFun, ['', interval]);
  return rslt[0];
};

const TimeLevels = {
  scale: [24, 60, 60, 1],
  units: ['d ', 'h ', 'm ', 's ']
};
const secondsToString = interval => intervalToLevels(interval, TimeLevels);

If you call secondsToString(123456), you can get "1d 10h 17m 36s "

如果你打电话secondsToString(123456),你可以得到“1d 10h 17m 36s”

回答by user1063287

This answer builds upon on Andris' approachto this question, but it doesn't have trailing commas if lesser units are not present.

这个答案建立在Andris对这个问题的方法之上,但如果不存在较小的单位,它就没有尾随逗号。

It also borrows from this answer dealing with joining array values only if truthy:

它还借鉴了这个答案,仅在truthy以下情况下处理连接数组值:

https://stackoverflow.com/a/19903063

https://stackoverflow.com/a/19903063

I'm not a javascript god and it's probably horribly over-engineered, but hopefully readable and correct!

我不是 javascript 之神,它可能被过度设计了,但希望可读和正确!

function sformat(s) {

    // create array of day, hour, minute and second values
    var fm = [
        Math.floor(s / (3600 * 24)),
        Math.floor(s % (3600 * 24) / 3600),
        Math.floor(s % 3600 / 60),
        Math.floor(s % 60)
    ];

    // map over array
    return $.map(fm, function(v, i) {

        // if a truthy value
        if (Boolean(v)) {

            // add the relevant value suffix
            if (i === 0) {
                v = plural(v, "day");
            } else if (i === 1) {
                v = plural(v, "hour");
            } else if (i === 2) {
                v = plural(v, "minute");
            } else if (i === 3) {
                v = plural(v, "second");
            }

            return v;
        }

    }).join(', ');

}

function plural(value, unit) {

    if (value === 1) {
        return value + " " + unit;
    } else if (value > 1) {
        return value + " " + unit + "s";
    }

}


console.log(sformat(60)); // 1 minute
console.log(sformat(3600)); // 1 hour
console.log(sformat(86400)); // 1 day
console.log(sformat(8991)); // 2 hours, 29 minutes, 51 seconds

If you needed to convey the duration more 'casually' in words, you could also do something like:

如果您需要更“随意”地用文字表达持续时间,您还可以执行以下操作:

var remaining_duration = sformat(117);
// if a value is returned, add some prefix and suffix 
if (remaining_duration !== "") {
    remaining_duration = "about " + remaining_duration + " left";
}
$(".remaining_duration").text(remaining_duration);

// returns 'about 1 minute, 57 seconds left'

回答by CommandoScorch

Here is my solution, a simple function that will round to the nearest second!

这是我的解决方案,一个简单的函数,将四舍五入到最接近的秒!

var returnElapsedTime = function(epoch) {
  //We are assuming that the epoch is in seconds
  var hours = epoch / 3600,
      minutes = (hours % 1) * 60,
      seconds = (minutes % 1) * 60;
  return Math.floor(hours) + " hours, " + Math.floor(minutes) + " minutes, " + Math.round(seconds) + " seconds";
}

回答by Svetoslav Marinov

I've tweaked the code that Andris posted https://stackoverflow.com/users/3564943/andris

我已经调整了 Andris 发布的代码https://stackoverflow.com/users/3564943/andris

            // https://stackoverflow.com/questions/36098913/convert-seconds-to-days-hours-minutes-and-seconds
        function app_ste_36098913_countdown_seconds_to_hr(seconds) {
            seconds = seconds || 0;
            seconds = Number(seconds);
            seconds = Math.abs(seconds);

            var d = Math.floor(seconds / (3600*24));
            var h = Math.floor(seconds % (3600*24) / 3600);
            var m = Math.floor(seconds % 3600 / 60);
            var s = Math.floor(seconds % 60);
            var parts = new Array();

            if (d > 0) {
                var dDisplay = d > 0 ? d + ' ' + (d == 1 ? "day" : "days") : "";
                parts.push(dDisplay);
            }

            if (h > 0) {
                var hDisplay = h > 0 ? h + ' ' + (h == 1 ? "hour" : "hours") : "";
                parts.push(hDisplay)
            }

            if (m > 0) {
                var mDisplay = m > 0 ? m + ' ' + (m == 1 ? "minute" : "minutes") : "";
                parts.push(mDisplay)
            }

            if (s > 0) {
                var sDisplay = s > 0 ? s + ' ' + (s == 1 ? "second" : "seconds") : "";
                parts.push(sDisplay)
            }

            return parts.join(', ', parts);
        }

回答by Hektor

You will probably find using epoch timestamps more straightforward: As detailed here Convert a Unix timestamp to time in JavaScript, the basic method is like so:

您可能会发现使用纪元时间戳更简单:如在 JavaScript中将Unix 时间戳转换为时间的详细说明,基本方法如下:

                    <script>

                     // Create a new JavaScript Date object based on the timestamp
                            // multiplied by 1000 so that the argument is in milliseconds, not seconds.
                            var date1 = new Date();

                            alert ('easy trick to waste a few seconds...' + date1);


                            // var date = date2 - date1;

                            // Hours part from the timestamp
                            var hours1 = date1.getHours();
                            // Minutes part from the timestamp
                            var minutes1 = "0" + date1.getMinutes();
                            // Seconds part from the timestamp
                            var seconds1 = "0" + date1.getSeconds();



                            var date2 = new Date();

                            // Hours part from the timestamp
                            var hours2 = date2.getHours();
                            // Minutes part from the timestamp
                            var minutes2 = "0" + date2.getMinutes();
                            // Seconds part from the timestamp
                            var seconds2 = "0" + date2.getSeconds();



                            // Will display time in 10:30:23 format
                            // var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);


                            var  elapsedHrs = hours2 - hours1;
                            var  elapsedMin = minutes2.substr(-2) -minutes1.substr(-2);
                            var elapsedSec = seconds2.substr(-2) - seconds1.substr(-2);                                

                            var elapsedTime = elapsedHrs + ' hours, ' + elapsedMin + ' minutes, ' + elapsedSec + ' seconds';

                            alert ('time between timestamps: ' + elapsedTime);

                    </script>

Be warned that this script needs some work since for now it will give negative values for things like date1 = 12:00:00 and date2 = 12:00:05, but I'll leave that to you fo now. You should rewrite your code to take a timestamp ( var x = new Date(); ) at the start of your timer and one whenever you are done/want to check elapsed time, and subtract the two before parsing out elapsed seconds, minutes, hours etc as required.

请注意,此脚本需要一些工作,因为现在它会为诸如 date1 = 12:00:00 和 date2 = 12:00:05 之类的东西提供负值,但我现在将其留给您。您应该重写代码以在计时器开始时使用时间戳( var x = new Date(); ),并且在您完成/想要检查经过时间时使用时间戳,并在解析经过的秒数,分钟数之前减去两者,小时等根据需要。