Skip to content

Instantly share code, notes, and snippets.

@puttputt
Created November 26, 2019 23:45
Show Gist options
  • Save puttputt/e016950e8213e83f450fad0e8ca46371 to your computer and use it in GitHub Desktop.
Save puttputt/e016950e8213e83f450fad0e8ca46371 to your computer and use it in GitHub Desktop.
Extending moment.Duration to have a long format humanized string
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