人类可读持续时间的格式?JavaScript

Format for human readable duration? JavaScript

本文关键字:格式 JavaScript 持续时间 人类      更新时间:2023-09-26

我有这个function用于人类可读的持续时间。

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

如何将r, x, y, zu放在一起,如果有两个以上,最后一个总是由and隔开,其余的由comma隔开。结果也是string类型。
例子:
"年"、"日"、"时"、"分"answers"秒"
"年"、"日"、"小时"answers"分钟"
"年"
"第二"
"分"answers"秒"
它继续……

我试图将它们放入array以便能够使用slice(),但它并没有返回所有可能组合的理想结果。由于

你在正确的轨道上的数组:

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

(我个人更喜欢牛津逗号["this, that, and the other"],但你的例子没有使用它,所以这是你要求的…)

<<p> 生活例子/strong>:

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>