28.6.10

Javascript timestamp formatting

I've ran into this scenario enough times that I think it's faster to post it and search it than opening an old file :)

Assume that you're working with a timestamp (number of milliseconds since January 1, 1970), for example:
var t = +new Date;

If you want to make that a relative time like "10 minutes ago", you can use this simple function:

function format(timestamp){
  var now = +new Date;
  var diff = (now - timestamp)/1000;
  if (diff < 60) return diff + ' seconds ago';
  if ((diff/=60) < 60) return Math.floor(diff) + ' minutes ago';
  if ((diff/=24) < 24) return Math.floor(diff) + ' hours ago';
  if ((diff/=7) < 7) return Math.floor(diff) + ' days ago';
  if ((diff/=4) < 4) return Math.floor(diff) + ' weeks ago';
  var date = new Date(timestamp);
  var month = ['January', 'February', 'March',
               'April', 'May', 'June', 'July',
               'August', 'September', 'October',
               'November', 'December'][date.getMonth()];
  var YEAR = 365*24*60*60;
  var year = (now - timestamp < YEAR) ? '' : ' ' + date.getFullYear();
  return (month) + ' ' + (date.getDate()) + year;
}
I hope you find this useful.

Update

Tinkering around, I noticed that blogger has this:
function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

No comments: