3.8. Finding the Day in a Week, Month, Year, or the Week Number in a Year3.8.1. ProblemYou want to know the day or week of the year, the day of the week, or the day of the month. For example, you want to print a special message every Monday, or on the first of every month. 3.8.2. SolutionUse the appropriate arguments to date( ) or strftime( ): print strftime("Today is day %d of the month and %j of the year."); print 'Today is day '.date('d').' of the month and '.date('z').' of the year.'; 3.8.3. DiscussionThe two functions date( ) and strftime( ) don't behave identically. Days of the year start with 0 for date( ), but with 1 for strftime( ). Table 3-4 contains all the day and week number format characters date( ) and strftime( ) understand. Table 3-4. Day and week number format characters
To print out something only on Mondays, use the w formatting character to date( ) or the %w string with strftime( ): if (1 == date('w')) { print "Welcome to the beginning of your work week."; } if (1 == strftime('%w')) { print "Only 4 more days until the weekend!"; } There are different ways to calculate week numbers and days in a week, so be careful to choose the appropriate one. The ISO standard (ISO 8601), says that weeks begin on Mondays and that the days in the week are numbered 1 (Monday) through 7 (Sunday). Week 1 in a year is the first week in a year with a Thursday in that year. This means the first week in a year is the first week with a majority of its days in that year. These week numbers range from 01 to 53. Other week number standards range from 00 to 53, with days in a year's week 53 potentially overlapping with days in the following year's week 00. As long as you're consistent within your programs, you shouldn't run into any trouble, but be careful when interfacing with other PHP programs or your database. For example, MySQL's DAYOFWEEK( ) function treats Sunday as the first day of the week, but numbers the days 1 to 7, which is the ODBC standard. Its WEEKDAY( ) function, however, treats Monday as the first day of the week and numbers the days from 0 to 6. Its WEEK( ) function lets you choose whether weeks should start on Sunday or Monday, but it's incompatible with the ISO standard. 3.8.4. See AlsoDocumentation on date( ) at http://www.php.net/date and strftime( ) at http://www.php.net/strftime; MySQL's DAYOFWEEK( ), WEEKDAY( ), and WEEK( ) functions are documented at http://www.mysql.com/doc/D/a/Date_and_time_functions.html. Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|