note 38743 added to function.date
| From: | blkgryffynatyahoo at rn2 dot php dot net | Date: | Mon, 05 Jan 2004 17:42:54 +0000 |
| Subject: | note 38743 added to function.date | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-62961@lists.php.net to get a copy of this message | ||
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
----
Manual Page -- http://www.php.net/manual/en/function.date.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+38743
Delete -- http://master.php.net/manage/user-notes.php?action=delete+38743&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+38743&report=yes
Search -- http://master.php.net/manage/user-notes.php