Last active
July 15, 2019 15:17
-
-
Save bvandenbon/dc2ba9508297b4b1a38877464fec4ace to your computer and use it in GitHub Desktop.
SecondsToTimePipe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment