note 56257 deleted from function.date by derick

From: Date: Sun, 15 Jan 2006 12:42:45 +0000
Subject: note 56257 deleted from function.date by derick
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-101828@lists.php.net to get a copy of this message
Note Submitter: trucex at gmail ---- In response to aedude (gordon from freepgs.net): I have modified your function so it makes more sense and is more useful. <?php function datediff($date1, $date2) { // $date1 is subtracted from $date2. // if $date2 is not specified, then current date is assumed. //Splits date apart list($date1_month, $date1_day, $date1_year) = split('[/.-]', $date1); if (!$date2) { $date2_year = date("Y"); //Gets Current Year $date2_month = date("m"); //Gets Current Month $date2_day = date("d"); //Gets Current Day } else { list($date2_month, $date2_day, $date2_year) = split('[/.-]', $date2); } $date1 = mktime(0,0,0,$date1_month, $date1_day, $date1_year); //Gets Unix timestamp for $date1 $date2 = mktime(0,0,0,$date2_month, $date2_day, $date2_year); //Gets Unix timestamp for $date2 $difference = $date2-$date1; //Calcuates Difference return floor($difference/60/60/24); //Calculates Days Old } ?> New Usage: <? //Get how many days since a file has been modified: echo "$file was modified " . datediff($filemtime($file), 0) . " days ago."; //Outputs: // Somefile.txt was modified 6 days ago. ?> Or <? $sally_bday = "11-10-87"; $frank_bday = "11-05-86"; echo "Frank is " . datediff($frank_bday, $sally_bday) . "days older than Sally."; //Outputs: //Frank is 370 days older than Sally. ?> As you can see, either example can be expanded upon greatly. Keep in mind this function does not do well with leap years or more precise time as-is, though it could be modified to do so if needed. A more practical use for this is to do something like delete files older than 30 days from a server, or see which file/value is older.

« previous php.notes (#101828) next »