gor*_*dyr 9 javascript momentjs
我有一个"剩余时间"计数器用于文件上传.计算剩余持续时间并将其转换为毫秒,如下所示:
var elapsedTime = e.timeStamp - timestarted;
var speed = e.loaded / elapsedTime;
var estimatedTotalTime = e.totalSize / speed;
var timeLeftInSeconds = (estimatedTotalTime - elapsedTime) / 1000;
Run Code Online (Sandbox Code Playgroud)
然后我构建一个数组,我打算将其构建为一个人性化的字符串.数组如下:
var time = {
years : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').years()),
months : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').months()),
days : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').days()),
hours : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').hours()),
minutes : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').minutes()),
seconds : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').seconds())
};
Run Code Online (Sandbox Code Playgroud)
这一切都很完美,如果我输出这样的数据的字符串表示如下:
console.log(time.years + ' years, ' + time.months + ' months, ' + time.days + ' days, ' + time.hours + ' hours, '+ time.minutes + ' minutes, ' + time.seconds + ' seconds');
Run Code Online (Sandbox Code Playgroud)
我返回一个很简单的剩余时间流,如下所示:
0 years, 0 months, 0 days, 0 hours, 1 minutes, 7 seconds
Run Code Online (Sandbox Code Playgroud)
我现在需要做的是将此输出人性化,以便根据剩余时间构建字符串.例如
等...等...
现在我知道moment.js具有自动人性化持续时间的能力,这对于单个值可以正常工作但是这可以有多个可能的值(小时/分钟/秒等)
如何使用moment.js或手动构建字符串来对这些数据进行人性化处理?
提前致谢.
我的HumanizeDuration.js库听起来就像你想要的那样:
humanizeDuration(1); // "1 millisecond"
humanizeDuration(3000); // "3 seconds"
humanizeDuration(2012); // "2 seconds, 12 milliseconds"
humanizeDuration(97320000); // "1 day, 3 hours, 2 minutes"
Run Code Online (Sandbox Code Playgroud)
看起来我的答案有点晚了,但也许它会帮助其他人看这个问题!
我认为你最好的选择是这样的:
function humanize(time){
if(time.years > 0){ return time.years + ' years and ' + time.months + ' months remaining';}
if(time.months > 0){ return time.months + ' months and ' + time.days + ' days remaining';}
if(time.days > 0){ return time.days + ' days and ' + time.hours + ' hours remaining';}
if(time.hours > 0){ return time.hours + ' hours and ' + time.minutes + ' minutes and ' + time.seconds + ' seconds remaining';}
if(time.minutes > 0){ return time.minutes + ' minutes and ' + time.seconds + ' seconds remaining';}
if(time.seconds > 0){ return time.seconds + ' seconds remaining';}
return "Time's up!";
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用此功能:
function humanize(time){
var o = '';
for(key in time){
if(time[key] > 0){
if(o === ''){
o += time[key] + ' ' + key + ' ';
}else{
return o + 'and ' + time[key] + ' ' + key + ' remaining';
}
}
}
return o + 'remaining';
}
Run Code Online (Sandbox Code Playgroud)
它返回"x <time> and y <time> remaining"2个最大值.(或者在最后一种情况下只有几秒钟.
| 归档时间: |
|
| 查看次数: |
13503 次 |
| 最近记录: |