So I've been looking for this functionality throughout the net and haven't found a solution that I could use to convert seconds to years, months, days, hours, minutes and seconds that could be represented as a string.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
I have came up with solution of a Pipe in Angular2, however I would like to get some feedback on things that could be done better to improve it.
Moreover maybe some other people will be in a need of this kind of pipe, so I'm just leaving it here to share.
import {Pipe} from "angular2/core";
@Pipe({
name: 'secondsToTime'
})
export class secondsToTimePipe{
times = {
year: 31557600,
month: 2629746,
day: 86400,
hour: 3600,
minute: 60,
second: 1
}
transform(seconds){
let time_string: string = '';
let plural: string = '';
for(var key in this.times){
if(Math.floor(seconds / this.times[key]) > 0){
if(Math.floor(seconds / this.times[key]) >1 ){
plural = 's';
}
else{
plural = '';
}
time_string += Math.floor(seconds / this.times[key]).toString() + ' ' + key.toString() + plural + ' ';
seconds = seconds - this.times[key] * Math.floor(seconds / this.times[key]);
}
}
return time_string;
}
}