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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37591076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:32:56  来源:igfitidea点击:

How to convert seconds to time string in angular2?

typescriptangularcode-snippetsangular2-pipe

提问by Zigmas

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.

因此,我一直在整个网络中寻找此功能,但还没有找到可用于将秒转换为可以表示为字符串的年、月、日、小时、分钟和秒的解决方案。

回答by Zigmas

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.

我想出了 Angular2 中管道的解决方案,但是我想得到一些关于可以做得更好的事情的反馈以改进它。

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