Book HomePHP CookbookSearch this book

16.6. Localizing Dates and Times

16.6.1. Problem

You want to display dates and times in a locale-specific manner.

16.6.2. Solution

Use strftime( )'s %c format string:

 print strftime('%c');

You can also store strftime( ) format strings as messages in your message catalog:

$MC = new pc_MC_es_US;
print strftime($MC->msg('%Y-%m-%d'));

16.6.3. Discussion

The %c format string tells strftime( ) to return the preferred date and time representation for the current locale. Here's the quickest way to a locale-appropriate formatted time string:

print strftime('%c');

This code produces a variety of results:

Tue Aug 13 18:37:11 2002     // in the default C locale
mar 13 ago 2002 18:37:11 EDT // in the es_US locale
mar 13 aoÛ 2002 18:37:11 EDT // in the fr_FR locale

The formatted time string that %c produces, while locale-appropriate, isn't very flexible. If you just want the time, for example, you must pass a different format string to strftime( ). But these format strings themselves vary in different locales. In some locales, displaying an hour from 1 to 12 with an A.M./P.M. designation may be appropriate, while in others the hour should range from 0 to 23. To display appropriate time strings for a locale, add elements to the locale's $messages array for each time format you want. The key for a particular time format, such as %H:%M, is always the same in each locale. The value, however, can vary, such as %H:%M for 24-hour locales or %I:%M %P for 12-hour locales. Then, look up the appropriate format string and pass it to strftime( ):

$MC = new pc_MC_es_US;

print strftime($MC->msg('%H:%M'));

Changing the locale doesn't change the time zone, it changes only the formatting of the displayed result.

16.6.4. See Also

Section 3.5 discusses the format strings that strftime( ) accepts; Section 3.12 covers changing time zones in your program; documentation on strftime( ) at http://www.php.net/strftime.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.