Created
November 26, 2019 23:45
-
-
Save puttputt/e016950e8213e83f450fad0e8ca46371 to your computer and use it in GitHub Desktop.
Extending moment.Duration to have a long format humanized string
This file contains 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 * as moment from 'moment'; | |
declare module 'moment' { | |
interface Duration { | |
humanizeLong(): string; | |
} | |
} | |
(moment.duration as any).fn.humanizeLong = function (): string { | |
const years = this.years(); | |
const months = this.months(); | |
const days = this.days(); | |
const hours = this.hours(); | |
const minutes = this.minutes(); | |
const durationArray: string[] = [ | |
!!years ? | |
years > 1 ? `${years} years` : `${years} year` | |
: '', | |
!!months ? | |
months > 1 ? `${months} months` : `${months} month` | |
: '', | |
!!days ? | |
days > 1 ? `${days} days` : `${days} day` | |
: '', | |
!!hours ? | |
hours > 1 ? `${hours} hours` : `${hours} hour` | |
: '', | |
!!minutes ? | |
minutes > 1 ? `${minutes} minutes` : `${minutes} minute` | |
: '' | |
]; | |
return durationArray.filter(val => val !== '').join(', '); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment