Home  >  Article  >  Backend Development  >  How Can I Format DateTime Objects with Locale-Specific Translations Using PHP\'s Intl Extension?

How Can I Format DateTime Objects with Locale-Specific Translations Using PHP\'s Intl Extension?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 13:51:10838browse

How Can I Format DateTime Objects with Locale-Specific Translations Using PHP's Intl Extension?

Locale-Aware DateTime Formatting

To format a DateTime object in a specific locale, it's essential to consider Locale::getDefault(). The Intl extension provides a convenient way to format dates and times while respecting locale settings.

Solution

The IntlDateFormatter class can be used to format dates with the desired locale. To achieve the desired format, which includes the German translation of "Tuesday," consider the following example:

$dt = new DateTime;

$formatter = new IntlDateFormatter('de_DE', IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
$formatter->setPattern('E d.M.yyyy');

echo $formatter->format($dt);

This code will output the date in a German-localized format, e.g., "Di. 4.6.2013" for today's date.

Additional Notes

  • The first argument to IntlDateFormatter is the locale string, such as 'de_DE' for German (Germany).
  • The format pattern used in setPattern() matches the SimpleDateFormat syntax. For more information, refer to https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.

The above is the detailed content of How Can I Format DateTime Objects with Locale-Specific Translations Using PHP\'s Intl Extension?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn