Convert seconds to days, hours, minutes and seconds

前端 未结 8 1447
陌清茗
陌清茗 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:11

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

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

    https://stackoverflow.com/a/19903063

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

    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'
    

提交回复
热议问题