Skip to content

Instantly share code, notes, and snippets.

@aj0strow
Created November 27, 2014 23:27
Show Gist options
  • Save aj0strow/2d321194facbb4de8af0 to your computer and use it in GitHub Desktop.
Save aj0strow/2d321194facbb4de8af0 to your computer and use it in GitHub Desktop.
Moment.js twitter-style fromNow
assert(typeof moment == 'function', 'moment dependency')
function gt (input, key) {
var dur = moment.duration(input, key)
return this.as('milliseconds') > dur.as('milliseconds')
}
function lt (input, key) {
var dur = moment.duration(input, key)
return this.as('milliseconds') < dur.as('milliseconds')
}
_.extend(moment.duration.fn, { gt: gt, lt: lt })
function fromNowTwitter () {
var ms = moment().diff(this)
assert(ms >= 0, 'date must be in the past')
var dur = moment.duration(ms, 'milliseconds')
switch (true) {
case dur.lt(1, 'minute'):
return Math.max(Math.floor(dur.as('seconds')), 1) + 's'
case dur.lt(1, 'hour'):
return Math.floor(dur.as('minutes')) + 'm'
case dur.lt(1, 'day'):
return Math.floor(dur.as('hours')) + 'h'
case dur.lt(1, 'year'):
return this.format('D MMM')
default:
return this.format('D MMM YYYY')
}
}
_.extend(moment.fn, { fromNowTwitter: fromNowTwitter })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment