note 38743 deleted from function.date by tomsommer

From: Date: Sat, 17 Jul 2004 13:21:29 +0000
Subject: note 38743 deleted from function.date by tomsommer
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-73443@lists.php.net to get a copy of this message
Note Submitter: blkgryffyn at yahoo ---- I did a quick search for something to tell me the difference between two dates (and times if applicable) and didn't like the ones I saw, or felt that they were somewhat incomplete, so I wrote this: <?php # Standard format dates and times $startdate = "10/30/02"; $starttime = "13:05:01"; $enddate = "12/30/03"; $endtime = "14:06:02"; # Break apart dates and times for mktime list($smonth,$sday,$syear) = explode("/",$startdate); list($emonth,$eday,$eyear) = explode("/",$enddate); list($shour,$sminute,$ssecond) = explode(":",$starttime); list($ehour,$eminute,$esecond) = explode(":",$endtime); # Number of seconds in each timeframe, 1 month = 30 days $secondsequiv = array("Years"=>31536000, "Months"=>2592000, "Days"=>86400, "Hours"=>3600, "Minutes"=>60); # How many seconds between two dates/times $stimestamp = mktime($shour,$sminute,$ssecond,$smonth,$sday,$syear); $etimestamp = mktime($ehour,$eminute,$esecond,$emonth,$eday,$eyear); $daydiff = $etimestamp - $stimestamp; # Just to make sure I didn't use $remainder somewhere else in my script and forgot if (isset($remainder)) unset($remainder); # Cycle through timeframes checking to see if number is large enough to be a full year/month/day/etc # If so, find out how many and store remainder for further processing # If not, set to zero and continue processing foreach ($secondsequiv as $timeframe=>$seconds) { if (isset($remainder)) { $checkvalue = $remainder; } else { $checkvalue = $daydiff; } if ($checkvalue >= $seconds) { $daydiffarr[$timeframe] = floor($checkvalue/$seconds); $remainder = $daydiff % $seconds; } else { $daydiffarr[$timeframe] = 0; } } # If $reminder is never used, then we're dealing with less than a minute's worth of time diff if (isset($remainder)) { $daydiffarr["Seconds"] = $remainder; } else { $daydiffarr["Seconds"] = $daydiff; } # Display results foreach ($daydiffarr as $timeframe=>$count) { echo "$timeframe = $count<br>\n"; } ?> This seems slightly more elegant and versatile than some of the other examples I saw. Forgive me if you have a better way and I missed it. Feel free to drop me a line if you have any questions. -Gryffyn

« previous php.notes (#73443) next »