Convert seconds to days, hours, minutes and seconds

前端 未结 8 1446
陌清茗
陌清茗 2020-12-03 16:45

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

It will display numbers when start button is click.Now I want this numbers converted to so

8条回答
  •  孤城傲影
    2020-12-03 17:17

    I've tweaked the code that Andris posted 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);
            }
    

提交回复
热议问题