Skip to content

Instantly share code, notes, and snippets.

@wiledal
Created November 8, 2013 10:07
Show Gist options
  • Select an option

  • Save wiledal/7368920 to your computer and use it in GitHub Desktop.

Select an option

Save wiledal/7368920 to your computer and use it in GitHub Desktop.
Gives you a nice date sentence from a timestamp
function getNiceDateFromTimestamp(timestamp) {
var splits = {
"second": [60 * 1000, 1000],
"minute": [60 * 60 * 1000, 60 * 1000],
"hour": [24 * 60 * 60 * 1000, 60 * 60 * 1000],
"day": [7 * 24 * 60 * 60 * 1000, 24 * 60 * 60 * 1000],
"week": [4 * 7 * 24 * 60 * 60 * 1000, 7 * 24 * 60 * 60 * 1000],
"month": [12 * 4 * 7 * 24 * 60 * 60 * 1000, 4 * 7 * 24 * 60 * 60 * 1000],
"year": [-1, 12 * 4 * 7 * 24 * 60 * 60 * 1000]
}
var sentence = "{number} {timetype} ago";
var today = new Date();
var then = new Date(timestamp);
var diff = today.getTime() - then.getTime();
var number = 0;
var timetype = "n/a";
for (split in splits) {
splitNum = splits[split][0];
splitDiv = splits[split][1];
if (diff < splitNum) {
number = Math.floor(diff/splitDiv);
timetype = split;
break;
}
if (splitNum == -1) {
number = Math.floor(diff/splitDiv);
timetype = split;
}
}
if (number > 1) timetype = timetype + "s";
return sentence.replace("{number}", number).replace("{timetype}", timetype);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment