In this tutorial I am going to teach you how to create your own relative date function.
We will use full relative dates like '1 minute ago', '1 hour ago' etc, but we will have exceptions for the time and a full date.
We start off creating a function, let's call it get_date. It should have two parameters, the time (unix time stamp) value and the type.
CODE:
|
<?
function get_date ( $timestamp , $type ) { // calculate the diffrence $timediff = time () - $timestamp ; |
Next up, calculating how many seconds are minutes, hours, days and weeks, transform the $timestamp into a relative date format and put the result in $returndate.
We all know that an hour has 3600 seconds, so if the diffrence is below 3600 we calculate in minutes. If the differnce is below 120, the returndate is 1 minute ago.
The calculation is done by dividing $timediff by 60.
CODE:
|
if ($timediff < 3600)
{ if ($timediff < 120) { $returndate = "1 minute ago"; } else { $returndate = intval($timediff / 60) . " minutes Ago."; } } |
If the diffrence is less than 86400, we can't be over one day, so we calculate in hours. The calculation is done by dividing $timediff by 3600.
CODE:
|
else if ($timediff < 7200)
{ $returndate = "1 hour ago."; } else if ($timediff < 86400) { $returndate = intval($timediff / 3600) . " hours ago."; } |
Next up: calculating the days. If the diffrence is less than 604800, means we're not at one week yet, so let's calculate in days. The calculation is $timediff / 86400.
CODE:
|
else if ($timediff < 172800)
{ $returndate = "1 day ago."; } else if ($timediff < 604800) { $returndate = intval($timediff / 86400) . " hours ago."; } |
Now we need to calculate the weeks, let's stop at 4 weeks. The calculation is $timediff divided by 604900.
CODE:
|
else if ($timediff < 1209600)
{ $returndate = "1 week ago."; } else if ($timediff < 3024000) { $returndate = intval($timediff / 604900) . " weeks ago."; } |
Now to finish it off, let's convert the date to normal date if the diffrence is over 3024000. Also, we will parse our special types of dates.
CODE:
|
else
{ $returndate = @date('n-j-Y', $timestamp); if($type=="fulldate") { $returndate = @date('n-j-y, H:i', $timestamp); } else if ($type=="time") { $returndate = @date('H:i', $timestamp); } } |
Almost done, close the function with a }.
CODE:
| } |
Now to use this function do the following:
CODE:
|
<?
// echoes relative date of 4 minutes ago echo "i was born like" . get_date ( time ()- 240 , "" ) . " " ; echo "it is now" . get_date ( time (), "fulldate" ) . " " ; echo "the time is" . get_date ( time (), "time" ) . " " ; ?> |
I hope you enjoyed reading this tutorial and learned from it. This tutorial has been created by Rick from PHPWned.












