简体   繁体   中英

Format for human readable duration? JavaScript

I have this function for human readable duration.

function formatDuration (seconds) {
    function numberEnding (number) {
        return (number > 1) ? 's' : '';
    }
    if (seconds > 0){
        var years = Math.floor(seconds / 31536000);
        var days = Math.floor((seconds % 31536000) / 86400);
        var hours = Math.floor(((seconds % 31536000) % 86400) / 3600);
        var minutes = Math.floor((((seconds % 31536000) % 86400) %  60);
        var second = (((seconds % 31536000) % 86400) % 3600) % 0;         
        var r = (years > 0 ) ? years + " year" + numberEnding(years) : ""; 
        var x = (days > 0) ? days + " day" + numberEnding(days) : "";
        var y = (hours > 0) ? hours + " hour" + numberEnding(hours) : "";
        var z = (minutes > 0) ? minutes + " minute" numberEnding(minutes) : "";
        var u = (second > 0) ? second + " second" + numberEnding(second) : "";
        var str = r + x + y + z + u

        return str
    }
    else {
        return "now"}
    }
}

How to put together r , x , y , z and u like if there are more than two the last one always seperated by and and the rest by comma . The result is also a string type.
example :
"year", "day", "hour", "minute" and "second"
"year", "day", "hour" and "minute"
"year"
"second"
"minute" and "second"
it goes on ...

I tried to put them into an array to be able to use slice() , but it does not return the desirable result for all possible combinations. Thanks

You're on the right track with the array:

var a = [];
//...push things as you go...
var str = a.length == 1 ? a[0] : a.slice(0, a.length - 1).join(", ") + " and " + a[a.length - 1];

(Personally I prefer the Oxford comma ["this, that, and the other"], but your example doesn't use it, so this does what you asked instead...)

Live Example :

 test(["this"]); test(["this", "that"]); test(["this", "that", "the other"]); function test(a) { var str = a.length == 1 ? a[0] : a.slice(0, a.length - 1).join(", ") + " and " + a[a.length - 1]; snippet.log("[" + a.join(", ") + "] => " + str); } 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM