search
HomeBackend DevelopmentPHP TutorialIntroducing an international calendar class in the PHP international component

In the internationalized component of PHP, there is also a date operation class that we do not commonly use, which is the calendar operation kind. It is said to be a calendar, but in fact most of it still operates on date and time, and is generally mainly used for date formatting and comparison. But usually we directly use date-related functions or DateTime-related classes to operate date-related functions, which is more convenient and flexible than this set of functions. Of course, for the purpose of learning, let’s take a brief look at it.

Formatting time

First let’s start with the formatting time.

$cal = IntlCalendar::createInstance(IntlTimeZone::getGMT());
var_dump(get_class($cal), IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));
// string(21) "IntlGregorianCalendar"
// string(66) "2020年11月18日星期三 格林尼治标准时间 上午12:58:14"

$cal1 = IntlCalendar::fromDateTime('2013-02-28 00:01:02 Europe/Berlin');
var_dump(get_class($cal1), IntlDateFormatter::formatObject($cal1, 'yyyy MMMM d HH:mm:ss VVVV', 'de_DE'));
// string(21) "IntlGregorianCalendar"
// string(41) "2013 Februar 28 00:01:02 Deutschland Zeit"

The createInstance() method of the IntlCalendar class will return an IntlCalendar object, and its parameters are optional, but must be of type TimeZone. The fromDateTime() method also generates an IntlCalendar object, but it can set a DateTime object or a date type string as a parameter.

As you can see, after using the get_class() method on the returned object, we can see that what is actually returned is an IntlGregorianCalendar Gregorian calendar object. At this time, you can use the formatObject() method of the IntlDateFormatter class to format the output content. It can specify the region. Different regional settings will display different formatting language results.

Return timestamp

echo IntlCalendar::getNow(), PHP_EOL; // 1605661094417

I won’t explain much, but this static method returns a timestamp with milliseconds.

As long as the internationalization-related functions are related to the time zone TimeZone, the calendar class is no exception.

ini_set('intl.default_locale', 'de_DE');
ini_set('date.timezone', 'Europe/Berlin');
$cal = IntlCalendar::createInstance();
print_r($cal->getTimeZone());
// IntlTimeZone Object
// (
//     [valid] => 1
//     [id] => Europe/Berlin
//     [rawOffset] => 3600000
//     [currentOffset] => 3600000
// )

echo $cal->getLocale(Locale::ACTUAL_LOCALE), PHP_EOL; // de
echo $cal->getLocale(Locale::VALID_LOCALE), PHP_EOL; // de_DE

Use getTimeZone() to get the current time zone information. There is no difference between getLocale() and the getLocale() method of other related functional classes in our previous article. You can take a look at what we have said before. Of course, in addition to ini_set(), this TimeZone property can also be modified directly through the setTimeZone() method of the object.

ini_set('intl.default_locale', 'zh_CN');
ini_set('date.timezone', 'Asia/Shanghai');
$cal = IntlCalendar::createInstance();
print_r($cal->getTimeZone());
// IntlTimeZone Object
// (
//     [valid] => 1
//     [id] => Asia/Shanghai
//     [rawOffset] => 28800000
//     [currentOffset] => 28800000
// )

$cal->setTimeZone('UTC');
print_r($cal->getTimeZone());
// IntlTimeZone Object
// (
//     [valid] => 1
//     [id] => UTC
//     [rawOffset] => 0
//     [currentOffset] => 0
// )

echo $cal->getLocale(Locale::ACTUAL_LOCALE), PHP_EOL; // zh
echo $cal->getLocale(Locale::VALID_LOCALE), PHP_EOL; // zh_Hans_CN

What does this mean? Let’s look at the code first.

$cal = IntlCalendar::fromDateTime('2020-02-15');
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //29
var_dump($cal->getMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //31
var_dump($cal->getActualMinimum(IntlCalendar::FIELD_DAY_OF_MONTH)); //1
var_dump($cal->getMinimum(IntlCalendar::FIELD_DAY_OF_MONTH)); //1
var_dump($cal->getLeastMaximum(IntlCalendar::FIELD_DAY_OF_MONTH));// 28 

$cal->add(IntlCalendar::FIELD_EXTENDED_YEAR, -1);
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //28
var_dump($cal->getMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //31
var_dump($cal->getActualMinimum(IntlCalendar::FIELD_DAY_OF_MONTH)); //1
var_dump($cal->getMinimum(IntlCalendar::FIELD_DAY_OF_MONTH)); //1
var_dump($cal->getLeastMaximum(IntlCalendar::FIELD_DAY_OF_MONTH));// 28

What the hell is this bunch upstairs? In fact, these methods return the maximum and minimum values ​​of the specified parameter field content. For example, what we are looking at is FIELD_DAY_OF_MONTH, which is how many days there are in the month. getActualMaximum() returns the actual value. For example, February 2020 has 29 days. getMaximum() returns the maximum value of the normal month, which is 31. getActualMinimum() and getMinimum() return the actual minimum value and the normal minimum value, which are both 1 for the month, and there will definitely be 1 day in each month. The getLeastMaximum() method is to obtain the minimum local maximum value of the field. How to understand it? The minimum number of days in February is 28 days, and its local maximum is 28 days, while other months have 30 and 31 days.

Start date of the week

This function is mainly used to set the day of the week when the start date of the week is. For example, for international standard time in Europe and the United States, Monday is not the beginning of the week, but Sunday is the first day of the week. You can find this problem in various calendar applications.

$cal = IntlCalendar::createInstance();
$cal->set(2020, 5, 30);
var_dump($cal->getFirstDayOfWeek()); // 1
echo IntlDateFormatter::formatObject($cal, <p>In the current time zone, the result returned by our getFirstDayOfWeek() is 1, that is, Monday is the starting point of the week, and the day of the week is calculated from 0. The set() method can set a specific date. Please note that the month also starts from 0. We then use IntlDateFormatter::formatObject() to output the day of the week, the week of the month, and the week of the current year. Here we set June 30, 2020. The current date represented by 'cc' is Thursday in the middle of the week, which is the fourth day of the week (not the specified June 30, which is when we run the code time, so that we can view it after modification), the current week is the fifth week in the current month, and the current week is the 27th week in the whole year. What if we change the time this week starts? </p><pre class="brush:php;toolbar:false">$cal->setFirstDayOfWeek(3);
var_dump($cal->getFirstDayOfWeek());  // int(5)
echo IntlDateFormatter::formatObject($cal, <p>Well, 'cc' has become 1, and it is currently Monday. We are now in week 6 of the current month, since we now start the week on Thursday. </p><h2 id="Calendar-comparison">Calendar comparison</h2><h3 id="Calendar-object-comparison">Calendar object comparison</h3><pre class="brush:php;toolbar:false">$cal1 = IntlCalendar::createInstance();
$cal2 = IntlCalendar::createInstance();
var_dump($cal1->equals($cal2)); // bool(true)
$cal2->setTime($cal1->getTime() + 1);
var_dump($cal1->equals($cal2)); // bool(false)

This is relatively simple. The properties inside the calendar object are different. Of course, the result returned by the equals() method is false.

Calendar object difference

In addition to comparing calendar objects, you can also obtain the difference information between two calendar times.

$cal1 = IntlCalendar::fromDateTime('2019-1-29 09:00:11');
$cal2 = IntlCalendar::fromDateTime('2020-03-01 09:19:29');
$time = $cal2->getTime();

echo "之前的时间: ", IntlDateFormatter::formatObject($cal1), "\n";
// 之前的时间: 2019年1月29日 上午9:00:11

printf(
    "两个时间的差别: %d year(s), %d month(s), "
  . "%d day(s), %d hour(s) and %d minute(s)\n",
    $cal1->fieldDifference($time, IntlCalendar::FIELD_YEAR),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_MONTH),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_DAY_OF_MONTH),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_HOUR_OF_DAY),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_MINUTE)
);
// 两个时间的差别: 1 year(s), 1 month(s), 1 day(s), 0 hour(s) and 19 minute(s)


echo "之后的时间: ", IntlDateFormatter::formatObject($cal1), "\n";
// 之后的时间: 2020年3月1日 上午9:19:11

You can see that using the fieldDifference() method you can get information related to the calendar object and the comparison date. It should be noted that after using fieldDifference(), all the original calendar objects become new date information.

Other information

View the regional setting keyword value set

print_r(iterator_to_array(IntlCalendar::getKeywordValuesForLocale('calendar', 'zh_CN', true)));
// Array
// (
//     [0] => gregorian
//     [1] => chinese
// )
print_r(iterator_to_array(IntlCalendar::getKeywordValuesForLocale('calendar', 'zh_CN', false)));
// Array
// (
//     [0] => gregorian
//     [1] => chinese
//     [2] => japanese
//     [3] => buddhist
//     [4] => roc
//     [5] => persian
//     [6] => islamic-civil
//     [7] => islamic
//     [8] => hebrew
//     [9] => indian
//     [10] => coptic
//     [11] => ethiopic
//     [12] => ethiopic-amete-alem
//     [13] => iso8601
//     [14] => dangi
//     [15] => islamic-umalqura
//     [16] => islamic-tbla
//     [17] => islamic-rgsa
// )

The first parameter of the getKeywordValuesForLocale() method can only be fixed to the calendar, followed by filling in the relevant areas. The content returned is the relevant word value information supported by the current language environment.

Regional Language Type

$cal = IntlCalendar::createInstance(NULL, '@calendar=ethiopic-amete-alem');
var_dump($cal->getType());
// string(19) "ethiopic-amete-alem"

$cal = new IntlGregorianCalendar();
var_dump($cal->getType());
// string(9) "gregorian"

Obviously, the getType() method returns the type of the specified language area information.

滚动日历

var_dump(IntlDateFormatter::formatObject($cal)); // string(31) "2020年11月18日 上午9:14:59"
$cal->roll(IntlCalendar::FIELD_DAY_OF_MONTH, true);
var_dump(IntlDateFormatter::formatObject($cal)); // string(31) "2020年11月19日 上午9:14:59"

使用 roll() 方法可以滚动或者说是卷动日历,在这里我们将日历滚动一天,也就是加了一天的时间。

转换为 DateTime 对象

var_dump($cal->toDateTime());
// object(DateTime)#4 (3) {
//     ["date"]=>
//     string(26) "2020-11-19 09:14:59.000000"
//     ["timezone_type"]=>
//     int(3)
//     ["timezone"]=>
//     string(13) "Asia/Shanghai"
//   }

使用 toDateTime() 方法就可以将当前的 IntlCalendar 对象转换成 DateTime 对象。

当前系统中支持的所有区域信息

print_r(IntlCalendar::getAvailableLocales());
// Array
// (
//     [0] => af
//     [1] => af_NA
//     [2] => af_ZA
//     [3] => agq
//     [4] => agq_CM
//     [5] => ak
//     [6] => ak_GH
//     [7] => am
//     [8] => am_ET
//     [9] => ar
//     ……
//     ……

getAvailableLocales() 返回的是当前系统中所有支持可用的 Locale 信息。

总结

关于日历类其实还有很多方法函数,但是看得人非常头晕,英文解释不多,资料也不清晰,所以这里就是简单的列举了一些内容。大家还是报以学习的心态了解即可,当需要使用到的时候可以快速地想起还这些功能就可以了。

推荐学习:《PHP视频教程

The above is the detailed content of Introducing an international calendar class in the PHP international component. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools