简体   繁体   中英

Special date format like 'today, July 12'

The output of the following routine is exactly what I want, but as a PHP beginner, I have had a hard time to get there and I'm not convinced with the steps I took. Can I achive the same result using only one DateFormatter and/or not having to poke the format with regex? Is there a possibility for an outright format definition?

<?php
    // display: (today, Juli 12th)

    $locales=array("en-gb","en","de-ch","ru","sv","pl","ca-es","es","it","fr","nl","pt","de");

    foreach ($locales as $locale) {

        $fmt1 = new IntlDateFormatter(
            $locale,
            IntlDateFormatter::RELATIVE_FULL,   // always 'today' 
            IntlDateFormatter::NONE,            // no time
            date_default_timezone_get(),
            IntlDateFormatter::GREGORIAN
        );

        $fmt2 = new IntlDateFormatter(
            $locale,
            IntlDateFormatter::FULL,            // everything
            IntlDateFormatter::NONE,            
            date_default_timezone_get(),
            IntlDateFormatter::GREGORIAN
        );

        // get 'today' from fmt1
        $today_string = $fmt1->format(time());

        // modify pattern of fmt2:
        $date_format = datefmt_get_pattern($fmt2);
        // get 'd to MMMM' or 'MMMM to d' from pattern, drop the rest
        $regEx="@(^.*?(d.*?MMMM|MMMM.*?d).*?$)@";
        datefmt_set_pattern($fmt2, preg_replace($regEx, '$2', $date_format)); 

        // use pattern to get output:
        $day_month = $fmt2->format(time());

        // concat and output
        $my_string = $today_string . ", " . $day_month;
        echo $my_string . PHP_EOL;
    }
?>

Output:

today, 12 July
today, July 12
heute, 12. Juli
сегодня, 12 июля
i dag, 12 juli
dzisiaj, 12 lipca
avui, 12 de juliol
hoy, 12 de julio
oggi, 12 luglio
aujourd’hui, 12 juillet
vandaag, 12 juli
hoje, 12 de julho
heute, 12. Juli

For the "today" string i can't find something better.... only setting them with the locales in the array.

Probably something like this instead of $fmt2 could be more readable

setlocale(LC_TIME, $locale);
$my_string = $today_string . ", " . date('d F');

Actually i don't remember date() takes setLocale in consideration... I'm sure about strftime() but it is deprecated in PHP 8.1.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM