Here is a function I have recently had to use. You pass a time/date string in strtotime format and the function will return a string with a date relative to today.
Examples of what the function can return;
- Today
- Yesterday
- Tomorrow
- In 2 days
- In 6 days
- 5 days ago
- Thursday 17 January
- Tuesday 4 January 2005
Example of usage;
//time stamp from my database etc
$my_timestamp = "2007-12-15 11:22:47";
//store the results of the function into $my_relative_time
$my_relative_time = relative_date(strtotime($my_timestamp ));
//output
echo $my_relative_time ;
The Function;
//Relative Date Function
function relative_date($time) {
$today = strtotime(date('M j, Y'));
$reldays = ($time - $today)/86400;
if ($reldays >= 0 && $reldays < 1) {
return 'Today';
} else if ($reldays >= 1 && $reldays < 2) {
return 'Tomorrow';
} else if ($reldays >= -1 && $reldays < 0) {
return 'Yesterday';
}
if (abs($reldays) < 7) {
if ($reldays > 0) {
$reldays = floor($reldays);
return 'In ' . $reldays . ' day' . ($reldays != 1 ? 's' : '');
} else {
$reldays = abs(floor($reldays));
return $reldays . ' day' . ($reldays != 1 ? 's' : '') . ' ago';
}
}
if (abs($reldays) < 182) {
return date('l, j F',$time ? $time : time());
} else {
return date('l, j F, Y',$time ? $time : time());
}
}
This is exactly what I needed. Thank you!
No problem I am glad it helped
hello bro
$my_relative_time = function relative_date(strtotime($my_timestamp ));
in this line you are calling function and you wrote function this is not write correct it to
$my_relative_time = relative_date(strtotime($my_timestamp ));
Thank you, very useful code.
Was going to spend some time coding that myself. Thanks so much!
No problem, glad it helped
Thank you this one i want …
Its still useful! Thanks!