简体   繁体   中英

How to format hour and minute in Chinese with PHP

I need to display a time in Chinese format with PHP.

I already try to use strftime :

setlocale(LC_TIME, "zh_CN");
echo strftime("%a, %Y %B %d");

It's work for date and display : 二, 2013 十一月 05

but for time :

setlocale(LC_TIME, "zh_CN");
echo strftime("%H %M");

display : 14 30

But 2:30pm have to be displayed like : 下午2时30分 for zh_CN and 下午2時半 for zh_HK

Did you kwon a solution or a php library to do that ?

Thx

PS : a javascript solution on client side can be good also ;)

I don't get the exact output you want but this is normally a good job for the intl extension:

<?php

$locales = array(
    'en_US',
    'en_GB',
    'zh_CN',
    'zh_HK',
);

$date = new DateTime('14:30');
foreach($locales as $locale){
    $fmt = new IntlDateFormatter($locale, IntlDateFormatter::NONE, IntlDateFormatter::SHORT);
    echo $fmt->format($date) . PHP_EOL;
}

... prints:

2:30 PM
14:30
下午2:30
下午2:30

If you stick to strftime you'd have to use %I ("Two digit representation of the hour in 12-hour format") rather than %H ("Two digit representation of the hour in 24-hour format") together with %p/%P ("AM/PM"). There's also %X ("Preferred time representation based on locale, without the date").

If you don't really need to support many languages, writing your own date formatter would be a sensible alternative.

As for JavaScript, I always see Moment.js recommended here but I haven't used it.

PHP gives inconsistent results when it comes to Chinese time support.

The solution which worked for me is to output the time ISO format and use jQuery and moment.js to get very close to the perfect solution to deal with internationalised time:

In php output your time to a <span> .

echo '<span date="'.date('c').'" moment-format="LT">'
    .date('h:n').'</span>';

where date('c') returns the ISO formatted date and moment-format defines the format moment.js should use to replace the ISO time

In Javascript you simply replace all the time formats :

    moment.lang('zh-cn'); // or zh-tw
    $('span[moment-format]').each(function(index, element) {
        if($(this).attr('date'))
        {
            $(this).html(
                moment().format($(this).attr('moment-format'))
            );
        }
    });

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