How to convert seconds to time string in angular2?

依然范特西╮ 提交于 2019-12-07 17:07:18

问题


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


来源:https://stackoverflow.com/questions/37591076/how-to-convert-seconds-to-time-string-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!