How to convert seconds to time string in angular2?

2019-05-11 02:40发布

问题:

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;
    }
}