Created
April 8, 2013 15:54
-
-
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.
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
/** | |
* 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much for making this Open Source. We benefited greatly from this.