Skip to content

Instantly share code, notes, and snippets.

@iuliaL iuliaL/duration.ts
Last active Mar 28, 2018

Embed
What would you like to do?
Duration or time elapsed formatter using moment js (i.e 34 hours and 5 minutes, 1 hour 1 minute)
function getDuration(startTime: Date, endTime: Date): string {
const milliseconds = moment(endTime).diff(startTime);
const duration = moment.duration(milliseconds);
const durationAsHours: number = Math.floor(duration.asHours());
const restInMinutes: number = duration.minutes();
const hours: string =
durationAsHours > 1
? `${durationAsHours} hours and `
: durationAsHours > 0
? `${durationAsHours} hour and `
: '';
const minutes: string = restInMinutes === 1
? `${restInMinutes} minute`
: `${restInMinutes} minutes`;
// if less than 1 minute show just the seconds
const minutesOrSeconds = milliseconds >= 60000
? minutes
: `${moment.duration(milliseconds).seconds()} seconds`;
return `${hours}${minutesOrSeconds}`;
}
/*
Reference: https://stackoverflow.com/questions/18623783/get-the-time-difference-between-two-datetimes?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.