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

Typescript 如何在angular2中将秒转换为时间字符串?,typescript,angular,code-snippets,angular2-pipe,Typescript,Angular,Code Snippets,Angular2 Pipe,因此,我一直在网上寻找这个功能,但还没有找到一个解决方案,可以将秒转换为年、月、日、时、分、秒,并用字符串表示 我已经提出了Angular2中管道的解决方案,但是我想得到一些可以更好地改进它的反馈 此外,也许其他人会需要这种管道,所以我把它留在这里与大家分享 import {Pipe} from "angular2/core"; @Pipe({ name: 'secondsToTime' }) export class secondsToTimePipe{ times = {

因此,我一直在网上寻找这个功能,但还没有找到一个解决方案,可以将秒转换为年、月、日、时、分、秒,并用字符串表示

我已经提出了Angular2中管道的解决方案,但是我想得到一些可以更好地改进它的反馈

此外,也许其他人会需要这种管道,所以我把它留在这里与大家分享

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

也不是所有的年份都一样长。闰年呢?谢谢你的链接,这就是我发布它的原因——为了得到一些反馈。闰年对我来说也是有问题的,我以一个普通年份为例,它解决了我的问题,因为我用它来查看一些活动持续的时间。再次感谢您的反馈。