Recipe 19.5. Localizing Dates and Times

19.5.1. Problem

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

19.5.2. Solution

Use strftime( )'s %c format string: print strftime('%c');. This format string displays a full time-and-date stamp in a locale-appropriate manner.

You can also store strftime( ) format strings as messages in your message catalog and pass the results to strftime( ), as in Example 19-13.

Using a message catalog with strftime( )

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

19.5.3. Discussion

The %c format string tells strftime( ) to return the preferred date and time representation for the current locale. It produces different results depending on the locale:

Sat May 13 13:53:31 2006      // in the default C locale Sam 13 Mai 2006 13:53:31 EDT  // in the de_AT locale sam 13 mai 2006 13:53:31 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( ), as shown in Example 19-14.

Using time formatting with a message catalog

<?php $MC = new pc_MC_es_US; print strftime($MC->msg('%H:%M')); ?>

Note that changing the locale doesn't change the time zone; it changes only the formatting of the displayed result.

19.5.4. See Also

Recipe 3.4 discusses the format strings that strftime( ) accepts; Recipe 3.11 covers changing time zones in your program; documentation on strftime( ) at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: