Automatically update time stamps with relative time format.
(function ($) {
$.fn.updateTime = function () {
this.each(function () {
var $this = $(this);
if ($this.parent().hasClass('stopUpdateTime') === false) {
$.update($this);
setInterval(function () {
$.update($this);
}, 60000);
}
});
}
var $lang = {
0: 'less than a minute ago',
1: '1 minute ago',
59: '%distance minutes ago',
118: 'an hour ago',
1439: '%r hours ago',
2879: 'Yesterday at %h:%i',
14567: '%l at %h:%i',
},
$default = '%d %f%y at %h:%i',
$days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
$months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
$.update = function ($this) {
if ($this.attr('title') != 'undefined') {
var $date = new Date($this.attr('title'));
var $timestamp = $this.attr('title');
if ($date == 'Invalid Date') {
$date = new Date($this.attr('title') * 1000);
$timestamp = ($this.attr('title') * 1000);
}
var $time = new Date();
var $distance = Math.round(Math.abs($time - $timestamp) / 60000);
var $return = '';
for (i in $lang) {
if ($return == '' && $distance <= i) {
var $r = Math.round($distance / 60),
$h = (($date.getHours() < 10) ? '0' : '') + $date.getHours(),
$i = (($date.getMinutes() < 10) ? '0' : '') + $date.getMinutes(),
$l = $days[$date.getDay()];
$return = $lang[i].replace(/%distance/i, $distance).replace(/%r/i, $r).replace(/%h/i, $h).replace(/%i/i, $i).replace(/%l/i, $l);
}
}
if ($return == '') {
var $d = (($date.getDate() < 10) ? '0' : '') + $date.getDate(),
$f = $months[$date.getMonth()],
$y = ($time.getFullYear() == $date.getFullYear()) ? '' : ' ' + $date.getFullYear(),
$h = (($date.getHours() < 10) ? '0' : '') + $date.getHours(),
$i = (($date.getMinutes() < 10) ? '0' : '') + $date.getMinutes();
$this.html(
$default.replace(/%d/i, $d).replace(/%f/i, $f).replace(/%y/i, $y).replace(/%h/i, $h).replace(/%i/i, $i));
} else $this.html($return);
}
}
})(jQuery);
$(document).ready(function () {
$('abbr.time').updateTime();
});
function timeInWords($timestamp) {
$distance = (round(abs(time() - $timestamp) / 60));
if ($distance <= 1) {
$return = ($distance == 0) ? 'less than a minute ago' : '1 minute ago';
}
elseif($distance < 60) {
$return = $distance.' minutes ago';
}
elseif($distance < 119) {
$return = 'an hour ago';
}
elseif($distance < 1440) {
$return = round(floatval($distance) / 60.0).' hours ago';
}
elseif($distance < 2880) {
$return = 'Yesterday at '.date('H:i', $timestamp);
}
elseif($distance < 14568) {
$return = date('l', $timestamp).' at '.date('H:i', $timestamp);
} else {
$return = date('d F', $timestamp).((date('Y') != date('Y', $timestamp) ? ' '.date('Y', $timestamp) : '')).' at '.date('H:i', $timestamp);
}
return '<abbr class="time" title="'.$timestamp.'">'.$return.'</abbr>';
}