3

How can I localize a date? I use PHP to output a custom date format, and I want to translate the components, such as the name of the month.

I am using the following code. Is there a better code I should use with Drupal?

global $language;
if ($language->language == 'ar') {
  setlocale(LC_TIME, 'ar_CA.UTF-8');
  echo strftime("%B %e, %G");
}
else {
  setlocale(LC_TIME, 'en_CA.UTF-8');
  print(date("l,F j, Y");
}
2

1 Answer 1

5

Using format_date(), the following format character are localized by Drupal:

  • %A (In English, AM and PM)
  • %a (am, pm)
  • %e (e.g. UTC, Atlantic/Azores)
  • %D (e.g. Mon, Sun)
  • %l (e.g. Monday, Sunday)
  • %M (e.g. Jan, Dec)
  • %T (e.g. EST, MDT)
  • %F (e.g. January, December)

Notice also that on admin/config/regional/date-time/locale, it is possible to change the long/medium/short formats used from format_date().

screenshot

Clicking on the "edit" link, you can change those formats for every language.

screenshot

Instead of the code you are using, you should simply use:

$date_str = format_date(time(), 'short');  // the short format, such as 01/16/2013 - 20:37 
$date_str = format_date(time(), 'medium');  // the medium format, such as Wed, 01/16/2013 - 20:37 
$date_str = format_date(time(), 'long');  // the long format, such as Wednesday, January 16, 2013 - 20:37 

The effective format used for the long, short, and medium formats are the ones set on admin/config/regional/date-time/locale for the language currently used to display the page.

1
  • What should I do if I already have a date value? I tried date_format(strtotime($date)); but it does not work!
    – SaidbakR
    Commented Jul 30, 2014 at 20:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.