如何在angular2中将秒转换为时间字符串?

Zig*_*mas 3 code-snippets typescript angular2-pipe angular

所以我一直在寻找网络中的这个功能,并没有找到我可以用来将秒转换为可以表示为字符串的年,月,日,小时,分钟和秒的解决方案.

Zig*_*mas 10

我在Angular2中提出了一个Pipe的解决方案,但是我想得到一些关于可以更好地改进它的事情的反馈.

也许其他人可能会需要这种管道,所以我只是把它留在这里分享.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这看起来更容易;-) http://stackoverflow.com/a/25279340/217408 (4认同)