Posts Tagged ‘date-time functions’

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. Here you can find a simple one coded by me. You can find a detailed documentation in PHPDoc format below in the code section.

Usage

The function takes three parameters. Only the first one is mandatory.
dateDiff($d1[, $d2=null [, $format="all"]);

First two parameters are dates in unix timestamp format or any string strtotime functions accepts. This means you can use time() function to take the time or you possibly can use MySQL data directly with this function. Click to find about strtotime function. It doesn’t matter which date is bigger. Always positive result is returned. The last parameter tells the function in what format the result should be returned. You can choose one of “second”, “minute”, “hour”, “day”, “week”, “month” or “year” as a format. If you use one of these, the function returns the result as an integer. If you don’t use this parameter or set it as “all”, an array containing all the format parameters above will be returned. You can try it with this code: print_r(dateDiff(time(), “2009-12-04″));

Examples

echo "now:".date("r",time())."";
echo "1: ".dateDiff("20090401040302", time(), "month")." months";
echo "2: ".dateDiff(time(), "2009-07-23 04:00:00", "hour")." hours";
echo "3: ".dateDiff("-3 day", "2009-07-23 04:00:00", "day")." days";
echo "4: ".dateDiff("2008-06-23", "2009-07-23", "years")." years";

Code

/**
 * finds the difference between dates.
 * usage: dateDiff($d1[, $d2=null [, $format="all"]);
 * examples:
 *     dateDiff("20090401040302");
 *     dateDiff("20090401040302", time(), "month");
 *     dateDiff(time(), "2009-07-23 04:00:00", "hour");
 *     dateDiff("-3 day", "2009-07-23 04:00:00");
 *     dateDiff("2008-06-23", "2009-07-23", "years");
 *
 * @param mixed $d1     first date. can be unix timestamp or any date string
 *                      strtotime accepts.
 * @param mixed $d2     second date. if it is empty or not given,
 *                      the function uses the current time. which date is bigger or
 *                      smaller doesn't matters. can be an unix timestamp or any
 *                      date string strtotime accepts.
 * @param str $format   one of "second", "minute", "hour", "day", "week",
 *                      "month", "year", "all".
 *                      if it is empty or set as "all", all the types are
 *                      calculated and an array is returned. if not, result
 *                      is returned in specified format as an integer.
 * @return mixed        difference between dates as int or array depending on
 *                      the value of $format. if result is array, it contains
 *                      these parameters: "second", "minute", "hour", "day",
 *                      "week", "month", "year"
 */
function dateDiff($d1, $d2=null, $format="all"){
    if($d2==null){
        $d2=$d1;
        $d1=time();
    }

    if(!is_int($d1)) $d1=strtotime($d1);
    if(!is_int($d2)) $d2=strtotime($d2);
    $d=abs($d1-$d2);

    $format=strtolower($format);
    if(empty($format) || $format=="*") $format="all";
    if(strrpos($format, 's')==strlen($format)-1){
        $format=substr($format, 0, strlen($format)-1);
    }

    $result = array();

    if($format=="all" || $format=="day")    $result["day"]   = floor($d/(60*60*24));
    if($format=="all" || $format=="month")  $result["month"] = floor($d/(60*60*24*30));
    if($format=="all" || $format=="year")   $result["year"]  = floor($d/(60*60*24*365));
    if($format=="all" || $format=="week")   $result["week"]  = floor($d/(60*60*24*7));
    if($format=="all" || $format=="hour")   $result["hour"]  = floor($d/(60*60));
    if($format=="all" || $format=="minute") $result["minute"]= floor($d/60);

    if($format!="all") return $result[$format];
    else return $result;
}

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 simle format.

Click here for turkish version


/**
 * 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";
}