Skip to content

Instantly share code, notes, and snippets.

@Chris927
Created July 8, 2017 10:14
Show Gist options
  • Save Chris927/0ca684122cebcbd550e79e60919e4a88 to your computer and use it in GitHub Desktop.
Save Chris927/0ca684122cebcbd550e79e60919e4a88 to your computer and use it in GitHub Desktop.
How to use momentjs to reasonably cleanly format a duration
// inspired by https://github.com/moment/moment/issues/1048#issuecomment-23998922
const m = require('moment')
const displayDuration = (start, end) => {
const diff = end.diff(start)
const hours = end.diff(start, 'hour')
return hours === 0
? m.utc(diff).format('m [mins]')
: m.utc(diff).format('h [hour' + (hours > 1 ? 's' : '') + ' and] m [mins]')
}
// demo
const start = m() // is the current date/time
const end = m(start).add(13, 'minute')
console.log(displayDuration(start, end))
end.add(60, 'minute')
console.log(displayDuration(start, end))
end.add(2, 'hour')
console.log(displayDuration(start, end))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment