Home  >  Article  >  Backend Development  >  What are the date-related functions in PHP?

What are the date-related functions in PHP?

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-07-05 14:56:512023browse

Date-related operation functions are the functions we most often come into contact with in our daily work development. Of course, most students may use the two functions date() and time() the most. We won’t talk about these two functions today, and maybe we won’t talk about them in subsequent articles. After all, they are too commonly used.

What are the date-related functions in PHP?

In the study of manual documents, I want to discover some interesting functions or functions that I have never been exposed to, so the functions we are learning today may not be familiar to everyone. How have they been used? There may even be many that you have never seen.

Time zone class related functions

First of all, it is an object of the time zone class. It can help us get some information related to the current time zone.

$timezone = new DateTimeZone('Asia/Shanghai');
var_dump($timezone);
// object(DateTimeZone)#1 (2) {
//     ["timezone_type"]=>
//     int(3)
//     ["timezone"]=>
//     string(13) "Asia/Shanghai"
//   }

When instantiating this DateTimeZone time zone class, you need to pass a time zone parameter. What we give here is the general Chinese time zone setting. Although our international standard time zone is Beijing time in the East Eighth District, in the time zone format in PHP, our time zone is named after Shanghai.

This time zone class can directly obtain the positioning information of the currently specified time zone. For example, the positioning information of Asia/Shanghai is directly positioned to Shanghai.

// 时区相关的定位信息
var_dump($timezone->getLocation());
// array(4) {
//     ["country_code"]=>
//     string(2) "CN"
//     ["latitude"]=>
//     float(31.23333)
//     ["longitude"]=>
//     float(121.46666)
//     ["comments"]=>
//     string(12) "Beijing Time"
//   }

You can obtain the time zone positioning information through getLocation(). The query result of longitude and latitude is the center of Shanghai. The comments field also clearly indicates that the current time zone is Beijing time.

// 时区名称
var_dump($timezone->getName());
// string(13) "Asia/Shanghai"

// 相对于 GMT 的时差
var_dump($timezone->getOffset(new DateTime('now', $timezone)));
// int(28800)

// 所有时区转换信息
var_dump($timezone->getTransitions(time()));
// array(1) {
//     [0]=>
//     array(5) {
//       ["ts"]=>
//       int(1601168813)
//       ["time"]=>
//       string(24) "2020-09-27T01:06:53+0000"
//       ["offset"]=>
//       int(28800)
//       ["isdst"]=>
//       bool(false)
//       ["abbr"]=>
//       string(3) "CST"
//     }
//   }

The getName() method obtains the name of the current time zone, which goes without saying. getOffset() obtains the difference from the International Greenwich Mean Time (GMT), which is the time interval from the meridian. What is returned here is seconds, which is exactly 8 hours after conversion to hours.

The getTransitions() function returns the time of all time zone conversions. The time I tested was in the morning. The returned time field content is Greenwich time, and the offset field returns the difference from GMT time. GMT time is consistent with UTC time. If we come into contact with these two terms in our daily study and work, we can regard them as the same concept.

The standard name of UTC time is Coordinated Universal Time. Based on the International Atomic Time, the standard time of countries around the world is adjusted based on it, and the original intention of GMT is to position it as the prime meridian. Mean solar time, UTC also uses this meridian as the basis for time zone division. However, according to strict standards, they are not completely equal. You can check the specific content by yourself, but for our daily development, they can be regarded as equivalent.

// 包含 dst (夏令时),时差和时区信息的关联数组
var_dump(DateTimeZone::listAbbreviations());
// array(144) {
//     ["acdt"]=>
//     array(6) {
//       [0]=>
//       array(3) {
//         ["dst"]=>
//         bool(true)
//         ["offset"]=>
//         int(37800)
//         ["timezone_id"]=>
//         string(18) "Australia/Adelaide"
//       }
//       [1]=>
//       array(3) {
//         ["dst"]=>
//         bool(true)
//         ["offset"]=>
//         int(37800)
//         ["timezone_id"]=>
//         string(21) "Australia/Broken_Hill"
//       }
//     ……
//     ……

// 包含了所有时区标示符的索引数组
var_dump(DateTimeZone::listIdentifiers());
// array(426) {
//     [0]=>
//     string(14) "Africa/Abidjan"
//     [1]=>
//     string(12) "Africa/Accra"
//     [2]=>
//     string(18) "Africa/Addis_Ababa"
//     [3]=>
//     string(14) "Africa/Algiers"
//     ……
//     ……

listAbbreviations() static method returns the time difference and time zone information related to daylight saving time. Summer time and winter time are also a living standard in Western countries. We have not had much contact with them, so I will not explain them here. Students who are doing cross-border projects or European and American outsourcing should be familiar with them. The listIdentifiers() method returns an index array containing all time zone identifiers. Here you can see all supported time zone information.

Date interval operation

Perhaps everyone has done some interval operation on date and time, such as the diff() method of DateTime object.

$today = new DateTime('2020-09-27');
$beforeYestoday = new DateTime("2020-09-25");
var_dump($today->diff($beforeYestoday));
// object(DateInterval)#5 (16) {
//     ["y"]=>
//     int(0)
//     ["m"]=>
//     int(0)
//     ["d"]=>
//     int(2)
//     ["h"]=>
//     int(0)
//     ["i"]=>
//     int(0)
//     ["s"]=>
//     int(0)
//     ["f"]=>
//     float(0)
//     ["weekday"]=>
//     int(0)
//     ["weekday_behavior"]=>
//     int(0)
//     ["first_last_day_of"]=>
//     int(0)
//     ["invert"]=>
//     int(1)
//     ["days"]=>
//     int(2)
//     ["special_type"]=>
//     int(0)
//     ["special_amount"]=>
//     int(0)
//     ["have_weekday_relative"]=>
//     int(0)
//     ["have_special_relative"]=>
//     int(0)
//   }

As can be seen from the printed results, the diff() object returns a DateInterval object. This is the protagonist of our section. There is not much explanation about the attributes it prints out. The field names are already very intuitive, and the values ​​are the specific differences.

$interval = new DateInterval("P2D");
var_dump($interval);
// object(DateInterval)#2 (16) {
//     ["y"]=>
//     int(0)
//     ["m"]=>
//     int(0)
//     ["d"]=>
//     int(2)
//     ["h"]=>
//     int(0)
//     ["i"]=>
//     int(0)
//     ["s"]=>
//     int(0)
//     ["f"]=>
//     float(0)
//     ["weekday"]=>
//     int(0)
//     ["weekday_behavior"]=>
//     int(0)
//     ["first_last_day_of"]=>
//     int(0)
//     ["invert"]=>
//     int(0)
//     ["days"]=>
//     bool(false)
//     ["special_type"]=>
//     int(0)
//     ["special_amount"]=>
//     int(0)
//     ["have_weekday_relative"]=>
//     int(0)
//     ["have_special_relative"]=>
//     int(0)
//   }

Did you see it? The printed content is consistent with the content of the object returned by the diff() method above, but its constructor parameters are strange. That's right, when we instantiate a DateInterval object ourselves, we need to define its interval information for it. This interval information is what we pass in through the parameters of the constructor.

P2D means an interval of 2 days. It must first start with a P, and then it can have date content such as Y, M, and D. If time content is needed, a T is required, followed by H and M. , S these contents. For example, P2Y4DT6H8M represents the time interval of 2 years, 4 days, 6 hours and 8 minutes. For specific rules, please refer to the instructions in the document: https://www.php.net/manual/zh/dateinterval.construct.php.

$interval = new DateInterval("P2Y4DT6H8M");
var_dump($interval);
// object(DateInterval)#5 (16) {
//     ["y"]=>
//     int(2)
//     ["m"]=>
//     int(0)
//     ["d"]=>
//     int(4)
//     ["h"]=>
//     int(6)
//     ["i"]=>
//     int(8)
//     ["s"]=>
//     int(0)
//     ["f"]=>
//     float(0)
//     ["weekday"]=>
//     int(0)
//     ["weekday_behavior"]=>
//     int(0)
//     ["first_last_day_of"]=>
//     int(0)
//     ["invert"]=>
//     int(0)
//     ["days"]=>
//     bool(false)
//     ["special_type"]=>
//     int(0)
//     ["special_amount"]=>
//     int(0)
//     ["have_weekday_relative"]=>
//     int(0)
//     ["have_special_relative"]=>
//     int(0)
//   }

We can also return interval objects through date data in the form of field strings, such as:

// 从日期语句创建时间间隔
var_dump(DateInterval::createFromDateString('2 days'));
// object(DateInterval)#3 (16) {
//     ["y"]=>
//     int(0)
//     ["m"]=>
//     int(0)
//     ["d"]=>
//     int(2)
//     ["h"]=>
//     int(0)
//     ["i"]=>
//     int(0)
//     ["s"]=>
//     int(0)
//     ["f"]=>
//     float(0)
//     ["weekday"]=>
//     int(0)
//     ["weekday_behavior"]=>
//     int(0)
//     ["first_last_day_of"]=>
//     int(0)
//     ["invert"]=>
//     int(0)
//     ["days"]=>
//     bool(false)
//     ["special_type"]=>
//     int(0)
//     ["special_amount"]=>
//     int(0)
//     ["have_weekday_relative"]=>
//     int(0)
//     ["have_special_relative"]=>
//     int(0)
//   }

In addition, when outputting after obtaining the object, the DateInterval object also provides us with a format () method can output date information in a format like the printf() function, and the formatter used here is still the date formatter.

var_dump($interval->format('%y %d %h %i'));
// string(7) "2 4 6 8"

The output content is actually the corresponding date and time differences in the attributes.

Time period related functions

After talking about the time interval, let’s take a look at the time period. What is the concept of time cycle? For example, if we want to obtain the date every three days, we can use time period-related classes to process it.

$start = new DateTime('2020-09-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2020-09-30');
$daterange = new DatePeriod($start, $interval ,$end);
var_dump($daterange);
// object(DatePeriod)#7 (6) {
//     ["start"]=>
//     object(DateTime)#8 (3) {
//       ["date"]=>
//       string(26) "2020-09-01 00:00:00.000000"
//       ["timezone_type"]=>
//       int(3)
//       ["timezone"]=>
//       string(13) "Asia/Shanghai"
//     }
//     ["current"]=>
//     NULL
//     ["end"]=>
//     object(DateTime)#9 (3) {
//       ["date"]=>
//       string(26) "2020-09-30 00:00:00.000000"
//       ["timezone_type"]=>
//       int(3)
//       ["timezone"]=>
//       string(13) "Asia/Shanghai"
//     }
//     ["interval"]=>
//     object(DateInterval)#10 (16) {
//       ["y"]=>
//       int(0)
//       ["m"]=>
//       int(0)
//       ["d"]=>
//       int(7)
//       ["h"]=>
//       int(0)
//       ["i"]=>
//       int(0)
//       ["s"]=>
//       int(0)
//       ["f"]=>
//       float(0)
//       ["weekday"]=>
//       int(0)
//       ["weekday_behavior"]=>
//       int(0)
//       ["first_last_day_of"]=>
//       int(0)
//       ["invert"]=>
//       int(0)
//       ["days"]=>
//       bool(false)
//       ["special_type"]=>
//       int(0)
//       ["special_amount"]=>
//       int(0)
//       ["have_weekday_relative"]=>
//       int(0)
//       ["have_special_relative"]=>
//       int(0)
//     }
//     ["recurrences"]=>
//     int(1)
//     ["include_start_date"]=>
//     bool(true)
//   }


foreach($daterange as $date){
    echo $date->format("Ymd"), PHP_EOL;
}
// 20200901
// 20200908
// 20200915
// 20200922
// 20200929

首先设定了开始时间和结束时间以及一个时间间隔对象,然后用它们做为参数来生成一个 DatePeriod 时间周期对象。它是一个实现了迭代器的对象,所以我们可以直接遍历它,结果就是以 P7D ,也就是 7 天为间隔的一组日期数据。

var_dump($daterange->getDateInterval());
// object(DateInterval)#11 (16) {
//     ["y"]=>
//     int(0)
//     ["m"]=>
//     int(0)
//     ["d"]=>
//     int(7)
//     ["h"]=>
//     int(0)
//     ["i"]=>
//     int(0)
//     ["s"]=>
//     int(0)
//     ["f"]=>
//     float(0)
//     ["weekday"]=>
//     int(0)
//     ["weekday_behavior"]=>
//     int(0)
//     ["first_last_day_of"]=>
//     int(0)
//     ["invert"]=>
//     int(0)
//     ["days"]=>
//     bool(false)
//     ["special_type"]=>
//     int(0)
//     ["special_amount"]=>
//     int(0)
//     ["have_weekday_relative"]=>
//     int(0)
//     ["have_special_relative"]=>
//     int(0)
//   }

var_dump($daterange->getStartDate());
// object(DateTime)#11 (3) {
//     ["date"]=>
//     string(26) "2020-09-01 00:00:00.000000"
//     ["timezone_type"]=>
//     int(3)
//     ["timezone"]=>
//     string(13) "Asia/Shanghai"
//   }
var_dump($daterange->getEndDate());
// object(DateTime)#11 (3) {
//     ["date"]=>
//     string(26) "2020-09-30 00:00:00.000000"
//     ["timezone_type"]=>
//     int(3)
//     ["timezone"]=>
//     string(13) "Asia/Shanghai"
//   }

它的这一堆方法其实返回的就是我们定义的那些构造参数信息。另外,它还可以指定从开始日期往后按照时间间隔返回几条信息。

$period = new DatePeriod($start, $interval, 4);
foreach($period as $date){
    echo $date->format("Ymd"), PHP_EOL;
}
// 20200901
// 20200908
// 20200915
// 20200922
// 20200929

var_dump($period->getRecurrences());
// int(4)

recurrences 参数的作用就是按照指定的时间间隔返回几条信息,这里我们是返回 9月1号 之后每次间隔 7 天的 4 条信息,和上面的内容一样。这时我们修改构造函数的值为其它数量,比如修改为 2 ,那么就只会返回到 9月15号 的信息了。它不会受到结束日期的约束,可以返回从开始日期到指定数量之后的所有信息,大家可以自己尝试一下。

总结

今天学习的内容不知道大家有没有接触过,反正我是只用过 diff() 方法来处理过日期之间的差值问题,而且也并没有注意到过它返回的这个对象具体的内容。

而另外两个对象则是压根没有印象,完全就是没听说过的感觉。所以说,平常多刷刷手册还是非常有帮助的,今天学习的内容又让我们知道了很多东西,而且 DatePeriod 在具体的业务实现中是肯定会有使用场景的。学习不止,后面我们要学习的内容依然精彩。

测试代码:

https://github.com/zhangyue0503/dev-blog/blob/master/php/202009/source/12.PHP中的日期相关函数(一).php

推荐学习:php视频教程

The above is the detailed content of What are the date-related functions in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete