Skip to content

Instantly share code, notes, and snippets.

@jasonalderman
Last active November 29, 2017 22:02
Show Gist options
  • Save jasonalderman/cbbd65d84b51ec1355dcab6381f40938 to your computer and use it in GitHub Desktop.
Save jasonalderman/cbbd65d84b51ec1355dcab6381f40938 to your computer and use it in GitHub Desktop.
Subtracts a date from the current time, and presents it (like Twitter) as "2s" or "2m" or "2h" ago, or as a date.
var getTimeAgo = function(datestring) {
// Takes in any datestring that can be used with the Date() constructor:
// e.g., "10/22/15" or "Wed Nov 29 2015 13:42:33 GMT-0800 (PST)"
// and outputs a date like Twitter's datetimestamps.
var d1 = new Date();
var d2 = new Date(datestring);
var timeAgo = d1.getTime()-d2.getTime();
if ((timeAgo/1000/60/60/24) >= 1) {
// return full date: "Nov 10" if same year, or "10 Nov 2015"
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
if (d2.getFullYear() !== d1.getFullYear()) {
return d2.getDate() + ' ' + months[d2.getMonth()] + ' ' + d2.getFullYear().toString().substr(2,2);
} else {
return months[d2.getMonth()] + ' ' + d2.getDate();
}
} else if ((timeAgo/1000/60/60) >= 1) {
// return hours if less than 24: "2h"
return ""+Math.floor(timeAgo/1000/60/60)+"h";
} else if ((timeAgo/1000/60) >= 1) {
// return minutes if less than 60: "17m"
return ""+Math.floor(timeAgo/1000/60)+"m";
} else if ((timeAgo/1000) >= 1) {
// return seconds if less than 60: "42s"
return ""+Math.floor(timeAgo/1000)+"s";
} else {
// otherwise, let's just say it was "now"
return "now";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment