Code:
<?php
function convertToUnixTimestamp($dcDate) {
# dcDate is in the format YYYYMMDDHHiiSS
$unixTimestamp = mktime(substr($dcDate,8,2), substr($dcDate,10,2), substr($dcDate,12,2), substr($dcDate,4,2), substr($dcDate,6,2), substr($dcDate,0,4));
return $unixTimestamp;
}
function relativeDate($targetDate) {
# Convert date format from YYYYMMDDHHiiSS to Unix Timestamp
$targetTimestamp = convertToUnixTimestamp($targetDate);
$currentTimestamp = time();
$difference = $currentTimestamp - $targetTimestamp;
# Date is from the Future
if ($difference < 0) {
$theDate = 'In The Future';
return $theDate;
}
switch ($difference) {
# Greater Than 30 Days
case ($difference > 2592000):
$theDate = date('j M Y',mktime(substr($targetDate,8,2), substr($targetDate,10,2), substr($targetDate,12,2), substr($targetDate,4,2), substr($targetDate,6,2), substr($targetDate,0,4)));
break;
# Week(s) Ago (Condition represents greater than 6 days)
case ($difference > 518400):
$theDate = round($difference/518400) . ' week' . (round($difference/518400) > 1 ? 's' : '' ) . ' ago';
break;
# Day(s) or Hour(s) Ago (Condition represents greater than 59mins in seconds)
case ($difference > 3540):
# Generate Midnight Timestamp
$midnightTimstamp = mktime(00, 01, 00, date("m"), date("d"), date("Y"));
$differenceYesterday = $midnightTimstamp - $targetTimestamp;
# Yesterday
if ( (round($differenceYesterday) < 86400) && ($differenceYesterday > 0) ) {
$theDate = 'yesterday ' . date('ga',mktime(substr($targetDate,8,2), substr($targetDate,10,2), substr($targetDate,12,2), substr($targetDate,4,2), substr($targetDate,6,2), substr($targetDate,0,4)));
# Day(s) Ago
} else if ($difference > 86400) {
$theDate = round($difference/86400) . ' day' . (round($difference/86400) > 1 ? 's' : '' ) . ' ago';
# Hour(s) Ago
} else {
$theDate = round($difference/3600) . ' hour' . (round($difference/3600) > 1 ? 's' : '' ) . ' ago';
}
break;
# Min(s) Ago
default:
$theDate = ceil($difference/60) . ' min' . (ceil($difference/60 > 1) ? 's' : '' ) . ' ago';
break;
}
return $theDate;
}
# 28 Aug 2009 20:30 and 40 secs
$targetDate = '20090828203040';
print relativeDate($targetDate);
?>
I store my dates in the database as an integer in the format YYYYMMDDHHiiSS (eg. 20090828190000). This means ordering complex queries by date becomes trivial but it also allows anyone to quickly view the date in the database without having to first convert it from a unix timestamp.
But what if you wanted to output the date in a human readable format like facebook or vbull (eg. 2 mins ago, yesterday 2pm)?
This relative date function:
- Takes a date field in the format YYYYMMDDHHiiSS.
- Converts it to a unix timestamp.
- Calculates how long ago the event occured relative to todays date and time.
- Returns the date in a human readable format.
.