Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Pipe, PipeTransform } from '@angular/core';
- @Pipe({
- name: 'secondsToTime'
- })
- export class SecondsToTimePipe implements PipeTransform {
- static factors = {
- year: 31557600,
- month: 2629746,
- day: 86400,
- hour: 3600,
- minute: 60,
- sec: 1
- }
- static showOnly = 3;
- transform(seconds: number) {
- if (seconds == null) return "";
- const { factors } = SecondsToTimePipe;
- let result = '';
- let skippedFirstSpace = false;
- let shown = 0;
- for (const key in factors) {
- if (!factors.hasOwnProperty(key)) continue;
- const factor = factors[key];
- const count = Math.floor(seconds / factor);
- if (count === 0) continue;
- // show only x parameters
- // (i.e. don't show miliseconds if we also display years, keep it concise).
- if (shown++ > SecondsToTimePipe.showOnly) break;
- // only start adding spaces after the first match.
- const space = skippedFirstSpace ? ' ' : '';
- skippedFirstSpace = true;
- // add an s to put words in plural.
- const plural = (count > 1) ? 's' : '';
- // put everything together.
- result += `${space}${count} ${key}${plural}`;
- seconds -= factor * count;
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement