How to localize date format in PHP

2 Answers

0 votes
// Use system locale
$locale = locale_get_default();   // same effect as setlocale(LC_TIME, "")

// Current timestamp
$now = time();

// Short date
$short = new IntlDateFormatter(
    $locale,
    IntlDateFormatter::SHORT,
    IntlDateFormatter::NONE
);

// Long date
$long = new IntlDateFormatter(
    $locale,
    IntlDateFormatter::FULL,
    IntlDateFormatter::NONE
);

// Time
$timeFmt = new IntlDateFormatter(
    $locale,
    IntlDateFormatter::NONE,
    IntlDateFormatter::MEDIUM
);

// Weekday name
$weekday = new IntlDateFormatter(
    $locale,
    IntlDateFormatter::FULL,
    IntlDateFormatter::NONE,
    null,
    null,
    "EEEE"
);

// Month name
$month = new IntlDateFormatter(
    $locale,
    IntlDateFormatter::FULL,
    IntlDateFormatter::NONE,
    null,
    null,
    "MMMM"
);

echo "--- Using system locale ($locale) ---\n";
echo "Short date : " . $short->format($now) . "\n";
echo "Long date  : " . $long->format($now) . "\n";
echo "Time       : " . $timeFmt->format($now) . "\n";
echo "Weekday    : " . $weekday->format($now) . "\n";
echo "Month name : " . $month->format($now) . "\n";



/*
run:

--- Using system locale (en_US) ---
Short date : 4/19/26
Long date  : Sunday, April 19, 2026
Time       : 9:25:04 AM
Weekday    : Sunday
Month name : April

*/

 



answered 16 hours ago by avibootz
0 votes
// Set the default timezone for all date/time functions in this script.
// This ensures consistent output regardless of server configuration.
date_default_timezone_set('Europe/Paris');


// Create a DateTime object representing the current moment,
// explicitly using the Europe/Paris timezone.
$dateTimeObj = new DateTime('now', new DateTimeZone('Europe/Paris'));


// Format the DateTime object using IntlDateFormatter::formatObject.
// This is the modern, recommended way to localize dates in PHP.
//
// Parameters:
// 1. The DateTime object to format.
// 2. A custom ICU date pattern (not PHP date() syntax!)
//    - 'eee'  → abbreviated weekday (lun, mar, mer…)
//    - 'd'    → day of month
//    - 'MMMM' → full month name
//    - 'y'    → 4‑digit year
//    - 'HH:mm' → 24‑hour time
//    - 'à'    → literal text (French style)
// 3. The locale ('fr' = French)
//
// This produces a fully localized French date string.
$dateFormatted = IntlDateFormatter::formatObject(
    $dateTimeObj,
    'eee d MMMM y à HH:mm',
    'fr'
);


// Capitalize the first letter of each word.
// French normally doesn't capitalize weekdays/months,
// but this matches your original output style.
echo ucwords($dateFormatted);



/*
run:

Dim. 19 Avril 2026 à 11:29

*/

 



answered 15 hours ago by avibootz
...