3.7. Finding the Day in a Week, Month, Year, or the Week Number in a Year

Problem

You 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.

Solution

Use 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.';

Discussion

The 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

Type

strftime( )

date( )

Description

Range

Day

%d

d

Day of the month, numeric

01-31

Day

%j

z

Day of the year, numeric

001-366 for strftime( ); 0-365 for date( )

Day

%u

Day of the week, numeric (Monday is 1)

1-7

Day

%w

w

Day of the week, numeric (Sunday is 0)

0-6

Day

%W

ISO 8601 day of the week, numeric (Monday is the first day of the week)

0-6

Week

%U

Week number in the year; numeric; first Sunday is the first day of the first week

00-53

Week

%V

W

ISO 8601:1988 week number in the year; numeric; week 1 is the first week that has at least four days in the current year; Monday is the first day of the week

01-53

To print out something only on Mondays, ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.