Page 516 - Beginning PHP 5.3
P. 516
Part III: Using PHP in Practice
Formatting Date Strings
Although computers like to work in timestamps, in many situations you need to convert a timestamp to
a string representation of a date. Common scenarios include displaying a date in a Web page, or passing
a date to another application that expects to receive a date string in a specified format.
PHP ’ s date() function lets you convert a timestamp to a date string. It works in a similar way to
idate() , in that you pass it a format string and a timestamp to work with (omit the timestamp to convert
the current date and time). The main difference is that the format string can contain multiple characters,
allowing you to generate a date string containing as many components of the date and time as you like.
You can also use additional formatting characters that are not available when using idate() .
Here ’ s a list of the date - related formatting characters allowed in date() ’ s format string:
Character Description
j The day of the month without leading zeros
d The 2 - digit day of the month, with a leading zero if appropriate
D The day of the week as a three - letter string (such as “ Mon ” )
l (lowercase ‘ L ’ The day of the week as a full word (such as “ Monday ” )
)
w The day of the week as a number (0=Sunday, 6=Saturday)
N The day of the week as an ISO - 8601 number (1=Monday, 7=Sunday)
S An English ordinal suffix to append to the day of the month ( “ st, ” “ nd, ”
“ rd, ” or “ th ” ). Often used with the j formatting character
z The day of the year (zero represents January 1)
W The 2 - digit ISO - 8601 week number in the year, with a leading zero if
appropriate. Weeks start on Monday. The first week is week number 01
M The month as a three - letter string (such as “ Jan ” )
F The month as a full word (such as “ January ” )
n The month as a number (1 – 12)
m The month as a two - digit number, with a leading zero if appropriate (01 – 12)
t The number of days in the month (28, 29, 30, or 31)
y The year as a two - digit number
Y The year as a four - digit number
478
9/21/09 9:15:29 AM
c16.indd 478
c16.indd 478 9/21/09 9:15:29 AM