3

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 Answer 1

11

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Also not all years are equally long. What about leap-years?
Thank you Günter for the link, this is the reason why I posted it - to get some feedback. Leap years were also questionable for me, I took the case of one common year and it solves me the problem because I'm using it to see the time duration which some activity lasted. Thanks for the feedback again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.