3.15. Generating Time Ranges3.15.1. ProblemYou need to know all the days in a week or a month. For example, you want to print out a list of appointments for a week. 3.15.2. SolutionIdentify your start date using time( ) and strftime( ). If your interval has a fixed length, you can loop through that many days. If not, you need to test each subsequent day for membership in your desired range. For example, a week has seven days, so you can use a fixed loop to generate all the days in the current week: // generate a time range for this week $now = time(); // If it's before 3 AM, increment $now, so we don't get caught by DST // when moving back to the beginning of the week if (3 < strftime('%H', $now)) { $now += 7200; } // What day of the week is today? $today = strftime('%w', $now); // How many days ago was the start of the week? $start_day = $now - (86400 * $today); // Print out each day of the week for ($i = 0; $i < 7; $i++) { print strftime('%c',$start_day + 86400 * $i); } 3.15.3. DiscussionA particular month or year could have a variable number of days, so you need to compute the end of the time range based on the specifics of that month or year. To loop through every day in a month, find the epoch timestamps for the first day of the month and the first day of the next month. The loop variable, $day is incremented a day at a time (86400 seconds) until it's no longer less than the epoch timestamp at the beginning of the next month: // Generate a time range for this month $now = time(); // If it's before 3 AM, increment $now, so we don't get caught by DST // when moving back to the beginning of the month if (3 < strftime('%H', $now)) { $now += 7200; } // What month is this? $this_month = strftime('%m',$now); // Epoch timestamp for midnight on the first day of this month $day = mktime(0,0,0,$this_month,1); // Epoch timestamp for midnight on the first day of next month $month_end = mktime(0,0,0,$this_month+1,1); while ($day < $month_end) { print strftime('%c',$day); $day += 86400; } 3.15.4. See AlsoDocumentation on time( ) at http://www.php.net/time and strftime( ) at http://www.php.net/strftime. Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|