我正在使用Moment Duration Format而且很棒。在某些情况下,我无法获得正确的字符串格式。
这些是我当前的字符串输出类型在
之下var dur = moment.duration(d, "minutes").format("h [hrs] m [min]");
这些都是正确的输出,我只想更改最终类型。
当存在小时且分钟 ZERO 时,我想修剪字符串以显示小时数
所以
2小时0分钟变为 2小时
我不确定从正则表达式开始的位置?我认为这可能是实现它的唯一方法吗?
感谢您的帮助
答案 0 :(得分:4)
使用包装器函数代替正则表达式,该函数检查对象是否有值,如果没有,则更新格式字符串。
function getFormattedString(duration) {
var format = "";
if (duration.hours()) format += "h [hrs] ";
if (duration.minutes()) format += "m [min] "
if (duration.seconds()) format += "s [sec] ";
return duration.format(format)
}
console.log(getFormattedString(moment.duration(20, "minutes")))
console.log(getFormattedString(moment.duration(100, "minutes")))
console.log(getFormattedString(moment.duration(120, "minutes")))
console.log(getFormattedString(moment.duration(3701, "seconds")))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
year
,days
等1 sec
和10 secs
。
function getFormattedDurationString(value, unit) {
const valueMap = [
{name:'years', value:'y', unitValue:'yr'},
{name:'days', value:'d', unitValue:'day'},
{name:'hours', value:'h', unitValue:'hr'},
{name:'minutes', value:'m', unitValue:'min'},
{name:'seconds', value:'s', unitValue:'sec'},
{name:'milliseconds', value:'s', unitValue:'ms', bypassPlural: true},
]
var duration = moment.duration(value, unit);
var format = valueMap.reduce(function(p,c){
var val = duration[c.name]();
if(val >0){
p += c.value + " [" + c.unitValue + (val > 1 && !c.bypassPlural ? "s":"") + "] ";
}
return p
}, "")
return duration.format(format)
}
console.log(getFormattedDurationString(20, "minutes"))
console.log(getFormattedDurationString(100, "minutes"))
console.log(getFormattedDurationString(120, "minutes"))
console.log(getFormattedDurationString(3701, "seconds"))
console.log(getFormattedDurationString(3701, "days"))
console.log(getFormattedDurationString(3701, "milliseconds"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>