[英]Format for human readable duration? JavaScript
我有此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
, z
和u
想,如果有两个以上的最后一个总是分隔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];
(我个人更喜欢使用牛津逗号[“ this,that,and other”],但是您的示例未使用它,所以这确实符合您的要求...)
现场示例 :
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.