SyntaxStudy
Sign Up
PHP Date Formatting & Localization
PHP Intermediate 9 min read

Date Formatting & Localization

PHP's built-in date() always produces English output. For localized date names, use the IntlDateFormatter class (part of the intl extension) or PHP's strftime() with setlocale().

  • IntlDateFormatter is the modern, recommended approach.
  • It formats dates according to any locale using ICU patterns.
Example
<?php
// Standard date() — always English
echo date('l, F j, Y'); // Monday, July 15, 2024

// IntlDateFormatter — locale-aware (requires intl extension)
$formatter = new IntlDateFormatter(
    'fr_FR',                         // locale
    IntlDateFormatter::FULL,          // date style
    IntlDateFormatter::NONE,          // time style
    'Europe/Paris'                    // timezone
);
echo $formatter->format(new DateTime('2024-07-15'));
// lundi 15 juillet 2024

// German locale
$de = new IntlDateFormatter('de_DE', IntlDateFormatter::LONG, IntlDateFormatter::NONE);
echo $de->format(new DateTime('2024-07-15')); // 15. Juli 2024

// Custom ICU pattern
$custom = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    null,
    null,
    'EEEE, MMMM d' // e.g. "Monday, July 15"
);
echo $custom->format(new DateTime('2024-07-15'));

// Relative timestamps without intl
function timeAgo(int $timestamp): string {
    $diff = time() - $timestamp;
    return match (true) {
        $diff < 60    => 'just now',
        $diff < 3600  => floor($diff / 60) . ' minutes ago',
        $diff < 86400 => floor($diff / 3600) . ' hours ago',
        default       => floor($diff / 86400) . ' days ago',
    };
}
echo timeAgo(time() - 3000); // 50 minutes ago
Pro Tip

Tip: IntlDateFormatter is far more powerful than strftime(), which was deprecated in PHP 8.1. If you need localized date names, install the intl extension and use IntlDateFormatter.