Learn the international date formatting operation in PHP

Time:2021-9-20

For the internationalization function, date related formatting is also an important play. After all, different time zones and countries have different ways to represent dates. Today we are mainly going to learn how to represent date related information internationally.

Date formatting

The first is the most direct formatting ability.

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
Echo "en_us format result is:" $FMT - > format (time()), PHP_ EOL;
// en_ The US format result is: Friday, November 20, 2020 at 4:45:06 pm Pacific standard time

$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL, 
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
Echo "de_de format result is:" $FMT - > format (intlcalendar:: createinstance()), PHP_ EOL;
// de_ The de Format result is: Freitag, 20. November 2020 um 16:45:06 nordamerikanische westk ü sten normalzeit

$fmt = new IntlDateFormatter( "zh-CN" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL, 
    'Asia/Shanghai',IntlDateFormatter::GREGORIAN  );
Echo "zh CN format result is:" $FMT - > format (time()), PHP_ EOL;
//ZH CN format result: 8:45:06 AM CST on Saturday, November 21, 2020

The intldateformatter object is the operation class for date formatting in the internationalization component. It has many construction parameters, but it is actually very simple. The first parameter is the country and region setting, and the second and third parameters are the display format of date and day respectively. This will be demonstrated in the next code. The fourth parameter is time zone setting, and the fifth parameter is time specification. Gregory time is specified here.

Use the format () method to format the date and time of the timestamp or calendar object. It can only accept and format these two types of parameters. It will output according to various parameters set by the intldateformatter object. For example, the output language is English, German, Chinese, etc., and the output time is the time zone (8:00 in China and 4:00 in the United States).

For the display format of date and time, we can use the constants of several intldateformatter classes, mainly including full, short, medium and long.

$fmt = new IntlDateFormatter( "zh-CN" ,IntlDateFormatter::SHORT, IntlDateFormatter::LONG, 
    'Asia/Shanghai',IntlDateFormatter::GREGORIAN  );
Echo "zh CN format result is:" $FMT - > format (time()), PHP_ EOL;
//ZH CN format result is: 2020 / 11 / 21 GMT + 8 am 8:45:06

In addition, the sixth parameter of the constructor can specify the formatting rules.

$fmt = new IntlDateFormatter( "zh-CN" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL, 
    'Asia/Shanghai',IntlDateFormatter::GREGORIAN, 'yyyy/MM/dd' );
Echo "zh CN format result is:" $FMT - > format (time()), PHP_ EOL;
//ZH CN format result: 2020 / 11 / 21

Formats the date according to the specified object

In the format () method above, we can see that only timestamp and calendar object types can be used. In fact, there is another more powerful formatting method, which is the formatobject () method. It can be inferred from the name that it formats the date data according to the specified object.

$cal = IntlCalendar::createInstance(new DateTimeZone('Asia/Shanghai'));
echo IntlDateFormatter::formatObject($cal),PHP_EOL;
// Nov 21, 2020, 8:45:06 AM
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL),PHP_EOL;
// Saturday, November 21, 2020 at 8:45:06 AM China Standard Time
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::NONE, IntlDateFormatter::FULL),PHP_EOL;
// 20201121 08:45 AM
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL, 'zh-CN'),PHP_EOL;
//Saturday, November 21, 2020 8:45:06 am China standard time
echo IntlDateFormatter::formatObject($cal, "d 'of' MMMM y", 'zh-CN'), PHP_EOL;
//21 of November 2020

The most common is still the formatting of calendar objects. You can see more parameters of the formatobject () method. It can also directly specify the format of date and time and related language settings. In addition, it can also specify rich output rules. For example, the output of our last piece of code is the day of the month. stayInternational calendar class in PHPIn this article, we have also used this method for testing. There are many custom syntax rules. You can consult ICU related documents yourself.

In addition to formatting the calendar class, the formatobject () method can also output the datetime object in date format.

$dt = new DateTime();
echo IntlDateFormatter::formatObject($dt),PHP_EOL;
// Nov 21, 2020, 8:45:06 AM

However, it should be noted that from the note of the official document, the speed of formatobject () is very slow. There is a gap of about 10 times between PHP5 and format () method, and about 3 times under php7. Therefore, if there are no special requirements, try not to use the formatobject () method to format the date and time.

De parse date string

And before we wereLearn PHP international digital format processingAs mentioned in, we can format the object or timestamp into a standard string format for display. Can we reverse this standard string format data?

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$arr = $fmt->localtime($fmt->format(time()));
print_r($arr);
// Array
// (
//     [tm_sec] => 1
//     [tm_min] => 59
//     [tm_hour] => 16
//     [tm_year] => 120
//     [tm_mday] => 20
//     [tm_wday] => 5
//     [tm_yday] => 325
//     [tm_mon] => 10
//     [tm_isdst] => 0
// )

echo $fmt->parse("Thursday, November 19, 2020 at 5:05:41 PM Pacific Standard Time"), PHP_EOL;
// 1605834341

The Localtime () method is used to parse the content of a given standard date. According to the initialization rules of intldateformatter, the content of the string is inversely output into an array, including year, month, day, hour, minute, second and other information. The parse () method directly converts the given content into the corresponding timestamp.

$fmt = new IntlDateFormatter( "zh-CN" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL, 
    'Asia/Shanghai',IntlDateFormatter::GREGORIAN );
$arr = $FMT - > Localtime ("Friday, November 20, 2020, 8:54:08 AM CST");
print_r($arr);
// Array
// (
//     [tm_sec] => 8
//     [tm_min] => 54
//     [tm_hour] => 8
//     [tm_year] => 120
//     [tm_mday] => 20
//     [tm_wday] => 5
//     [tm_yday] => 325
//     [tm_mon] => 10
//     [tm_isdst] => 0
// )

Echo $FMT - > parse ("Friday, November 20, 2020, 8:54:08 AM CST"), PHP_ EOL;
// 1605833648

Both Chinese and English are well supported.

Related attribute acquisition and setting

Calendar type information

For calendar types, there are only two types of calendars, Gregorian and traditional, which correspond to Gregorian and traditional calendars respectively. In the construction parameter, we can specify it through the fifth parameter, or we can use the setcalendar () method to set it during the use of the object. The getcalendar () method is used to obtain the date type information currently set.

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL, 
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo $fmt->getCalendar(), PHP_EOL; // 1
$fmt->setCalendar(IntlDateFormatter::TRADITIONAL);
echo $fmt->getCalendar(), PHP_EOL; // 0

Date and time type

//Date type acquisition and setting
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL, 
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo $fmt->getDateType(), PHP_EOL; // 0
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::SHORT, IntlDateFormatter::FULL, 
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo $fmt->getDateType(), PHP_EOL; // 3

//Time type acquisition and setting
echo $fmt->getTimeType(), PHP_EOL; // 0
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::SHORT, IntlDateFormatter::MEDIUM, 
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo $fmt->getTimeType(), PHP_EOL; // 2

For date and time types, we can only specify them through the parameters of the constructor, and the obtained value is also the value of the corresponding constant.

Regional language information

echo $fmt->getLocale(), PHP_EOL; // en
echo $fmt->getLocale(Locale::VALID_LOCALE), PHP_EOL; // en_US

I won’t explain this much. It has been mentioned in previous articles. It seems that these two methods will be included in the classes of internationalization related components.

Format rule acquisition and setting

We can specify the formatting rules in the sixth parameter of the constructor, and we can also set the object dynamically.

echo $fmt->getPattern(), PHP_EOL; // M/d/yy, h:mm:ss a
$fmt->setPattern('yyyyMMdd hh:mm:ss z');
echo $fmt->getPattern(), PHP_EOL; // yyyyMMdd hh:mm:ss z
echo $fmt->format(time()), PHP_EOL; // 20201120 04:59:01 PST

After setting the format rules with setpattern (), format () again is formatted with the new format rules.

time zone

First, let’s look at a gettimezoneid () method. It directly obtains the time zone content, that is, a string.

echo $fmt->getTimezoneId(), PHP_EOL; // America/Los_Angeles
// $fmt->setTimeZoneId('CN'); //  Php7 deleted
// echo $fmt->getTimezoneId(), PHP_EOL;

However, the settimezoneid () method has been deleted in php7. Now it is recommended to use the settimezone () method to set the time zone information. Let’s take a look at it right away.

var_dump($fmt->getTimezone());
// object(IntlTimeZone)#4 (4) {
//     ["valid"]=>
//     bool(true)
//     ["id"]=>
//     string(19) "America/Los_Angeles"
//     ["rawOffset"]=>
//     int(-28800000)
//     ["currentOffset"]=>
//     int(-28800000)
//   }

$fmt->setTimeZone('Asia/Shanghai');
var_dump($fmt->getTimezone());
// object(IntlTimeZone)#4 (4) {
//     ["valid"]=>
//     bool(true)
//     ["id"]=>
//     string(13) "Asia/Shanghai"
//     ["rawOffset"]=>
//     int(28800000)
//     ["currentOffset"]=>
//     int(28800000)
//   }

$fmt->setTimeZone('GMT+00:30');
var_dump($fmt->getTimezone());
// object(IntlTimeZone)#4 (4) {
//     ["valid"]=>
//     bool(true)
//     ["id"]=>
//     string(9) "GMT+00:30"
//     ["rawOffset"]=>
//     int(1800000)
//     ["currentOffset"]=>
//     int(1800000)
//   }

Different from the gettimezoneid () method, the gettimezone () method returns an intltimezone object. The official documents on the content of this object are incomplete, and many method parameters are not written. I can’t guess, so I won’t write articles on this object. You can consult relevant materials by yourself. However, for simple time zone setting, the settimezone () method can directly use strings as parameters. For example, in the above code, we modify the time zone of Los Angeles to Shanghai, China and GMT + 00:30. Correspondingly, if we output the time with format (), the standard time in the current time zone will prevail.

Get calendar object

When formatting data, we have a lot to do with calendar objects. Of course, we can get calendar information through the intldateformatter object.

$cal = $fmt->getCalendarObject();
var_dump(
    $cal->getType(),
    $cal->getTimeZone(),
    $cal->getLocale(Locale::VALID_LOCALE)
);
// string(9) "gregorian"
// object(IntlTimeZone)#3 (4) {
//   ["valid"]=>
//   bool(true)
//   ["id"]=>
//   string(9) "GMT+00:30"
//   ["rawOffset"]=>
//   int(1800000)
//   ["currentOffset"]=>
//   int(1800000)
// }
// string(5) "en_US"

Tolerance

Finally, let’s take a look at tolerance, which is actually a strict mode of operation. For example, if we define an error time, the operation in intldateformatter will not report an error, because it is handled with tolerance by default.

$fmt->setPattern('dd/mm/yyyy');
var_dump($fmt->isLenient()); // bool(true)
echo $fmt->parse('35/13/1955'), PHP_EOL;
// -470449020

Obviously, this date is a wrong date. Through the islenient () method, we can obtain whether the current state is tolerant processing. We will now cancel the ability of tolerance and see what the result will be.

$fmt->setLenient(FALSE);
echo $fmt->parse('35/13/1955'), PHP_EOL;
// 

echo $fmt->getErrorCode(), PHP_EOL; // 9
echo $fmt->getErrorMessage(), PHP_EOL; // Date parsing failed: U_PARSE_ERROR

The parse () method has no output. At the same time, you can also see the error message through geterrorcode () and geterrormessage (). This is the main capability of tolerant processing in the intldateformatter object.

summary

Today’s learning content is more and scattered, but it is mainly the content of the intldateformatter object. Number and date format are the most important functions of internationalization related functions, and can also be applied to our daily business development at any time. You can learn more about relevant knowledge.

Test code:

https://github.com/zhangyue0503/dev-blog/blob/master/php/202011/source/8. Learn the international date formatting operation in PHP

Reference documents:

https://www.php.net/manual/zh/class.intldateformatter.php

===============

Official account: hard core project manager

Add wechat / QQ friends: [xiaoyuezigonggong / 149844827] get free PHP and project management learning materials

Tiktok, official account, voice, headline search, hard core project manager.

Station B ID: 482780532