[英]Format for human readable duration? JavaScript
I have this function
for human readable duration. 我有此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"}
}
}
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
. 如何拼凑r
x
, y
, z
和u
想,如果有两个以上的最后一个总是分隔and
和其余的comma
。 The result is also a string
type. 结果也是string
类型。
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. 我试图将它们放入array
以能够使用slice()
,但是对于所有可能的组合,它都没有返回理想的结果。 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...) (我个人更喜欢使用牛津逗号[“ this,that,and other”],但是您的示例未使用它,所以这确实符合您的要求...)
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.