人类可读时间的格式? JavaScript

问题描述:

我有这个function人类可读的持续时间。人类可读时间的格式? JavaScript

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

如何放在一起rxyzu一样,如果有两个以上的最后一个总是and分隔和comma休息。结果也是string类型。
例如:
“年”, “日”, “小时”, “分” 和 “秒”
“年”, “日”, “小时” 和 “分”
“年”
“第二个”
‘分’和‘秒’
如此下去......

我试图把它们放进一个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]; 

(我个人更喜欢牛津逗号[“这个,那个,和其他”],但你的例子并不使用它,所以这确实你问什么,而不是...)

活生生的例子

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>