Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localize current time in PHP

Trying to display current time with PHP (using this):

$date = date('m/d/Y h:i:s a', time());                      
echo $date;

As simple as it gets. How do I localize it? I want to translate the months and days to Hebrew.

Thanks.

like image 655
Tomer Lichtash Avatar asked Sep 13 '09 22:09

Tomer Lichtash


2 Answers

Zend_Date is completely internationalized. You should check that out for a simple way to do it:

All full and abbreviated names of months and weekdays are supported for more than 130 languages. Methods support both input and the output of dates using the localized names of months and weekdays, in the conventional format associated with each locale.

like image 161
karim79 Avatar answered Sep 22 '22 16:09

karim79


Actually, I don't think it is quite possible in PHP 5.2 :-(

At least, not with what's bundled with/in PHP (There are libraries coded in PHP that you could use, though, like other answers pointed out)


With PHP 5.3, though, you have the IntlDateFormatter class, which does exactly what you want :

This class represents the ICU date formatting functionality. It allows users to display dates in a localized format or to parse strings into PHP date values using pattern strings and/or canned patterns.

For instance, using that class, like this :

echo IntlDateFormatter::create('fr_FR', IntlDateFormatter::FULL, IntlDateFormatter::FULL)->format(time(time())) . "\n";
echo IntlDateFormatter::create('fr_FR', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT)->format(time(time())) . "\n";

echo IntlDateFormatter::create('zh-Hant-TW', IntlDateFormatter::FULL, IntlDateFormatter::FULL)->format(time(time())) . "\n";
echo IntlDateFormatter::create('zh-Hant-TW', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT)->format(time(time())) . "\n";

echo IntlDateFormatter::create('en_US', IntlDateFormatter::FULL, IntlDateFormatter::FULL)->format(time(time())) . "\n";
echo IntlDateFormatter::create('en_US', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT)->format(time(time())) . "\n";

You'd get :

dimanche 9 novembre 2008 23:54:47 GMT+00:00
9 nov. 2008 23:54
2008年11月9日星期日 下午11時54分47秒 GMT+00:00
2008/11/9 下午 11:54
Sunday, November 9, 2008 11:54:47 PM GMT+00:00
Nov 9, 2008 11:54 PM

Which looks quite nice, doesn't it ?

Sad thing is PHP 5.3 is only a few months old, and not available on many hosting services... And will require testing (and probably fixes) for your application...


Thinking about it : maybe you can install the PECL intl extension on PHP 5.2, though, and get the same functionnality...

like image 29
Pascal MARTIN Avatar answered Sep 21 '22 16:09

Pascal MARTIN