Created
July 8, 2017 10:14
-
-
Save Chris927/0ca684122cebcbd550e79e60919e4a88 to your computer and use it in GitHub Desktop.
How to use momentjs to reasonably cleanly format a duration
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
// 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