Skip to content

Instantly share code, notes, and snippets.

@bespr
Created April 8, 2013 15:54
Show Gist options
  • Save bespr/5337906 to your computer and use it in GitHub Desktop.
Save bespr/5337906 to your computer and use it in GitHub Desktop.
Extend moment.js to return very short words for time differences. Same as moment().fromNow, but much shorter.
/**
* A little moment js "plugin" to allow very short relative times
* NOT: "26 minutes ago"
* BUT: "26m"
*
* Usage:
* var m = moment('2013-04-08 17:50:00', 'YYYY-MM-DD HH:mm:ss');
* console.log(m.fromNow()); // -> "3 minutes ago"
* console.log(m.fromNowShort()); // -> "3m"
*
* Beat Oberholzer, 8. April 2013
*/
; (function(moment) {
moment.fn.fromNowShort = function() {
var shortTimeStrings = {
s : "%ds",
m : "%dm",
h : "%dh",
d : "%dd",
y : "%dy"
};
var milliseconds = this.diff(moment()),
seconds = Math.round(Math.abs(milliseconds) / 1000),
minutes = Math.round(seconds / 60),
hours = Math.round(minutes / 60),
days = Math.round(hours / 24),
years = Math.round(days / 365),
args = seconds < 45 && ['s', seconds] ||
minutes < 45 && ['m', minutes] ||
hours < 22 && ['h', hours] ||
days <= 300 && ['d', days] ||
['y', years];
var rt = shortTimeStrings[args[0]];
return rt.replace(/%d/i, args[1] || 1);
}
}(moment));
@monarchwadia
Copy link

Thank you so much for making this Open Source. We benefited greatly from this.

@TaylorAckley
Copy link

Huge thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment