PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 3.5 Printing a Date or Time in a Specified Format

3.5.1 Problem

You need to print out a date or time formatted in a particular way.

3.5.2 Solution

Use date( ) or strftime( ):

print strftime('%c');
print date('m/d/Y');
Tue Jul 30 11:31:08 2002
07/30/2002

3.5.3 Discussion

Both date( ) and strftime( ) are flexible functions that can produce a formatted time string with a variety of components. The formatting characters for these functions are listed in Table 3-3. The Windows column indicates whether the formatting character is supported by strftime( ) on Windows systems.

Table 3-3. strftime( ) and date( ) format characters

Type

strftime( )

date( )

Description

Range

Windows

Hour

%H

H

Hour, numeric, 24-hour clock

00-23

Yes

Hour

%I

h

Hour, numeric, 12-hour clock

01-12

Yes

Hour

%k

 

Hour, numeric, 24-hour clock, leading zero as space

0-23

No

Hour

%l

 

Hour, numeric, 12-hour clock, leading zero as space

1-12

No

Hour

%p

A

AM or PM designation for current locale

 

Yes

Hour

%P

a

am/pm designation for current locale

 

No

Hour

 

G

Hour, numeric, 24-hour clock, leading zero trimmed

0-23

No

Hour

 

g

Hour, numeric, 12-hour clock, leading zero trimmed

0-1

No

Minute

%M

I

Minute, numeric

00-59

Yes

Second

%S

s

Second, numeric

00-61[1]

Yes

Day

%d

d

Day of the month, numeric

01-31

Yes

Day

%e

 

Day of the month, numeric, leading zero as space

1-31

No

Day

%j

z

Day of the year, numeric

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

Yes

Day

%u

 

Day of the week, numeric (Monday is 1)

1-7

No

Day

%w

w

Day of the week, numeric (Sunday is 0)

0-6

Yes

Day

 

j

Day of the month, numeric, leading zero trimmed

1-31

No

Day

 

S

English ordinal suffix for day of the month, textual

"st," "th," "nd," "rd"

No

Week

%a

D

Abbreviated weekday name, text for current locale

 

Yes

Week

%A

l

Full weekday name, text for current locale

 

Yes

Week

%U

 

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

00-53

Yes

Week

%V

W

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

01-53

No

Week

%W

 

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

00-53

Yes

Month

%B

F

Full month name, text for current locale

 

Yes

Month

%b

M

Abbreviated month name, text for current locale

 

Yes

Month

%h

 

Same as %b

 

No

Month

%m

m

Month, numeric

01-12

Yes

Month

 

n

Month, numeric, leading zero trimmed

1-12

No

Month

 

t

Month length in days, numeric

28, 29, 30, 31

No

Year

%C

 

Century, numeric

00-99

No

Year

%g

 

Like %G, but without the century

00-99

No

Year

%G

 

ISO 8601 year with century; numeric; the four-digit year corresponding to the ISO week number; same as %y except if the ISO week number belongs to the previous or next year, that year is used instead

 

No

Year

%y

y

Year without century, numeric

00-99

Yes

Year

%Y

Y

Year, numeric, including century

 

Yes

Year

 

L

Leap year flag (yes is 1)

0, 1

No

Timezone

%z

O

Hour offset from GMT, +/-HHMM (e.g., -0400, +0230)

-1200-+1200

Yes, but acts like %Z

Timezone

%Z

T

Time zone, name, or abbreviation; textual

 

Yes

Timezone

 

I

Daylight saving time flag (yes is 1)

0, 1

No

Timezone

 

Z

Seconds offset from GMT; west of GMT is negative, east of GMT is positive

-43200-43200

No

Compound

%c

 

Standard date and time format for current locale

 

Yes

Compound

%D

 

Same as %m/%d/%y

 

No

Compound

%F

 

Same as %Y-%m-%d

 

No

Compound

%r

 

Time in AM or PM notation for current locale

 

No

Compound

%R

 

Time in 24-hour notation for current locale

 

No

Compound

%T

 

Time in 24-hour notation (same as %H:%M:%S)

 

No

Compound

%x

 

Standard date format for current locale(without time)

 

Yes

Compound

%X

 

Standard time format for current locale(without date)

 

Yes

Compound

 

r

RFC 822 formatted date (e.g., "Thu, 22 Aug 2002 16:01:07 +0200")

 

No

Other

%s

U

Seconds since the epoch

 

No

Other

 

B

Swatch Internet time

 

No

Formatting

%%

 

Literal % character

 

Yes

Formatting

%n

 

Newline character

 

No

Formatting

%t

 

Tab character

 

No

[1] The range for seconds extends to 61 to account for leap seconds.

The first argument to each function is a format string, and the second argument is an epoch timestamp. If you leave out the second argument, both functions default to the current date and time. While date( ) and strftime( ) operate over local time, they each have UTC-centric counterparts (gmdate( ) and gmstrftime( )).

The formatting characters for date( ) are PHP-specific, but strftime( ) uses the C-library strftime( ) function. This may make strftime( ) more understandable to someone coming to PHP from another language, but it also makes its behavior slightly different on various platforms. Windows doesn't support as many strftime( ) formatting commands as most Unix-based systems. Also, strftime( ) expects its formatting characters to each be preceded by a % (think printf( )), so it's easier to produce strings with lots of interpolated time and date values in them.

For example, at 12:49 P.M. on July 15, 2002, the code to print out:

It's after 12 pm on July 15, 2002

with strftime( ) looks like:

print strftime("It's after %I %P on %B %d, %Y");

With date( ) it looks like:

print "It's after ".date('h a').' on '.date('F d, Y');

Non-date-related characters in a format string are fine for strftime( ), because it looks for the % character to decide where to interpolate the appropriate time information. However, date( ) doesn't have such a delimiter, so about the only extras you can tuck into the formatting string are spaces and punctuation. If you pass strftime( )'s formatting string to date( ):

print date("It's after %I %P on %B%d, %Y");

you'd almost certainly not want what you'd get:

131'44 pmf31eMon, 15 Jul 2002 12:49:44 -0400 %1 %P o7 %742%15, %2002

To generate time parts with date( ) that are easy to interpolate, group all time and date parts from date( ) into one string, separating the different components with a delimiter that date( ) won't translate into anything and that isn't itself part of one of your substrings. Then, using explode( ) with that delimiter character, put each piece of the return value from date( ) in an array, which is easily interpolated in your output string:

$ar = explode(':',date("h a:F d, Y"));
print "It's after $ar[0] on $ar[1]";

3.5.4 See Also

Documentation on date( ) at http://www.php.net/date and strftime( ) at http://www.php.net/strftime; on Unix-based systems, man strftime for your system-specific strftime( ) options; on Windows, see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_strftime.2c_.wcsftime.asp for strftime( ) details.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    3.1 Introduction
    Recipe 3.2 Finding the Current Date and Time
    Recipe 3.3 Converting Time and Date Parts to an Epoch Timestamp
    Recipe 3.4 Converting an Epoch Timestamp to Time and Date Parts
    Recipe 3.5 Printing a Date or Time in a Specified Format
    Recipe 3.6 Finding the Difference of Two Dates
    Recipe 3.7 Finding the Difference of Two Dates with Julian Days
    Recipe 3.8 Finding the Day in a Week, Month, Year, or the Week Number in a Year
    Recipe 3.9 Validating a Date
    Recipe 3.10 Parsing Dates and Times from Strings
    Recipe 3.11 Adding to or Subtracting from a Date
    Recipe 3.12 Calculating Time with Time Zones
    Recipe 3.13 Accounting for Daylight Saving Time
    Recipe 3.14 Generating a High-Precision Time
    Recipe 3.15 Generating Time Ranges
    Recipe 3.16 Using Non-Gregorian Calendars
    Recipe 3.17 Program: Calendar
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele