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.
Asked
Active
Viewed 1.2k times
1 Answers
11
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;
}
}

Zigmas
- 325
- 1
- 3
- 12
-
Also not all years are equally long. What about leap-years? – Günter Zöchbauer Jun 02 '16 at 12:00
-
1Thank you Günter for the link, this is the reason why I posted it - to get some feedback. Leap years were also questionable for me, I took the case of one common year and it solves me the problem because I'm using it to see the time duration which some activity lasted. Thanks for the feedback again. – Zigmas Jun 02 '16 at 12:19