Web 2.0 Style Relative Date Writing

07 November 2010

Some sites like Youtube use a simple formatting style in comments' date & times. Instead of writing long and detailed dates (like October 12, 2009 07:23 PM), they use relative dates like 3 days ago, 2 weeks ago, etc.

The code below does the same thing. It takes your date, in any format php's strtotime uses (which means, in most situations dates coming from your database can be used directly), and converts it into this simple format.

/**
 * finds passed time in a readable format like
 * "2 days ago", "5 years ago", etc...
 * Sample usage:
 *  echo relativeTime("2009-08-23 12:05:14");
 * @param str $dateStr  date to calculate. any format readable by
 *                      php's strtotime function is appropriate.
 *                      check out http://www.php.net/manual/tr/function.strtotime.php
 *                      for usage of strtotime.
 * @param str $now      default is null which means running time. this is the
 *                      bigger date which $dateStr is substracted from.
 * @return str
 */
function relativeTime($dateStr, $now=null){
    if(!$now) $now=time();
    $time=$now-strtotime($dateStr);

    if($time<0) return "";

    if($time<60){$no=$time; $str="second";}
    else if($time<3600){$no=$time/60; $str="minute";}
    else if($time<86400){$no=$time/(3600); $str="hour";}
    else if($time<86400*7){$no=$time/(86400); $str="day";}
    else if($time<86400*30){$no=$time/(86400*7); $str="week";}
    else if($time<86400*365){$no=$time/(86400*30); $str="month";}
    else {$no=$time/(86400*365); $str="year";}

    return round($no)." ".$str.((round($no)>1)?"s":"")." ago";
}

Web 2.0 Style Relative Date Writing

07 November 2010

Web 2.0 Style Relative Date Writing

Some sites like Youtube use a simple formatting style in comments' date & times. Instead of writing long and detailed dates (like October 12, 2009 07:23 PM), they use relative dates like 3 days ago, 2 weeks ago, etc.

Date & Time Difference in PHP

14 January 2010

Date & Time Difference in PHP

To calculate the difference between dates, PHP has a date_diff function but it only works in PHP version 5.3 and above. So we still need a date substraction function.

Remove a Directory and Its Content with PHP

09 January 2010

Remove a Directory and Its Content with PHP

The function below deletes directories with many options. You can delete directories recursively, delete only content of directories or remove files in a directory with regular expression.

Remove Accents In UTF-8 Strings

12 December 2009

Remove Accents In UTF-8 Strings

Some sites like Youtube use a simple formatting style in comments' date & times. Instead of writing long and detailed dates (like October 12, 2009 07:23 PM), they use relative dates like 3 days ago, 2 weeks ago, etc.