16.5. Localizing Dates and Times
Problem
You want to display dates and times in a locale-specific manner.
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'));
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 ...
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.