user14666 user14666 - 7 months ago 38
PHP Question

How to translate this date format

In a template (Drupal) php.tpl file I have the following:

print date('F j, Y', $comment->created);
print ' at ' . date('h:ia', $comment->created);

But It doesn't print a translation when the site is in a foreign language. How do I make it translate? Using the t() function? If so, how do I rewrite it to include it?

Any and all help is appreciated. :)


Isemi's 2nd solution below works just fine except for the year that prints a Y instead of the year. With a minor adjustment the code becomes:

$dateF = t(date('F', $comment->created));
$datej = t(date('j', $comment->created));
$dateY = t(date('Y', $comment->created));
print "{$datej} {$dateF} {$dateY}" . t(' at ') . date('H:i', $comment->created);

The "at" is easy to translate as it becomes a separate translatable string.


The date() function uses, I believe, the server's locale. You ought to change it in the current process, which may be awkward and could not work in all configurations.

You ought to retrieve the desired locale string, then:

setlocale(LC_TIME, 'it_IT'); // Depends on the client.

$datel = strftime("%F %j, %Y at %H:%i:%s", $comment->created);

but apart from the correct codes (I'm not too sure about %F and %j), you still have the problem of translating 'at', I think.

Alternatively you can get the date piecewise and translate it by parts:

$dateF = translate(date('F', $comment->created));
$datej = translate(date('j', $comment->created));

print "{$dateF} {$datej}, Y " . translate('at')
      . date('h:ia', $comment->created);

You could also use the Intl extension, see this answer.