Introduction to PHP date-related functions (1)

藏色散人
Release: 2023-04-10 10:14:01
forward
2816 people have browsed it

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. When studying the manual documents, I want to discover some interesting functions or functions that I have never been exposed to. Therefore, the functions we are learning today may not be used by everyone, and there may even be many functions that everyone has 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"
//   }
Copy after login
Copy after login

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"
//   }
Copy after login
Copy after login

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"
//     }
//   }
Copy after login
Copy after login

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"
//     ……
//     ……
Copy after login
Copy after login

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)
//   }
Copy after login
Copy after login

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)
//   }
Copy after login
Copy after login

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, M, and S content. 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)
//   }
Copy after login
Copy after login

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)
//   }
Copy after login
Copy after login

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"
Copy after login
Copy after login

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
Copy after login
Copy after login

首先设定了开始时间和结束时间以及一个时间间隔对象,然后用它们做为参数来生成一个 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"
//   }
Copy after login
Copy after login

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

$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)
Copy after login
Copy after login

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

总结

今天学习的内容不知道大家有没有接触过,反正我是只用过 diff() 方法来处理过日期之间的差值问题,而且也并没有注意到过它返回的这个对象具体的内容。而另外两个对象则是压根没有印象,完全就是没听说过的感觉。所以说,平常多刷刷手册还是非常有帮助的,今天学习的内容又让我们知道了很多东西,而且 DatePeriod 在具体的业务实现中是肯定会有使用场景的。学习不止,后面我们要学习的内容依然精彩。

测试代码:

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

参考文档:

https://www.php.net/manual/zh/book.datetime.php

各自媒体平台均可搜索【硬核项目经理】


php




阅读 46



本作品系原创,采用《署名-非商业性使用-禁止演绎 4.0 国际》许可协议




Introduction to PHP date-related functions (1)

硬核项目经理


32 声望

6 粉丝



0 条评论

得票数最新







你知道吗?







Introduction to PHP date-related functions (1)

#Hardcore Project Manager


32 Reputation

6 Fans

Follow the author







#Billboards













# Table of contents


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"
//   }
Copy after login
Copy after login

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"
//   }
Copy after login
Copy after login
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"
//     }
//   }
Copy after login
Copy after login
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"
//     ……
//     ……
Copy after login
Copy after login

listAbbreviations() 静态方法返回的是 夏令时 相关的时差和时区信息。夏令时 和 冬令时 也是西方国家的一种生活标准,我们接触的不多,这里就不做讲解了,对于做跨境项目或者欧美外包的同学应该不会陌生。listIdentifiers() 方法返回的是包含了所有时区标示符的索引数组,这里可以看到所有的支持的时区信息。

日期间隔操作

对时日期时间的间隔操作,或许大家多少都做过一点,比如 DateTime 对象的那个 diff() 方法。

$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)
//   }
Copy after login
Copy after login

从打印的结果可以看出,diff() 对象返回的是一个 DateInterval 对象。这个就是我们这节的主角了,关于它打印出来的这些属性内容就不多解释了,字段名已经非常直观了,值就是具体的差值。

$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)
//   }
Copy after login
Copy after login

看到没有?打印出来的内容和上面用 diff() 方法返回的对象的内容是一致的,但是它的构造函数的参数很奇怪。没错,当我们自己去实例化一个 DateInterval 对象时,需要为它定义它的间隔信息,这个间隔信息就是我们通过构造函数的参数传递进去的。P2D 的意思就是间隔 2 天,首先必须以一个 P 为开头,然后可以有 Y、M、D 这些日期内容,如果需要时间内容的话,需要一个 T 然后再跟上 H、M、S 这些内容。比如 P2Y4DT6H8M 表示的就是 2年4天6小时8分钟 的时间间隔。具体的规则大家还是去看文档中的说明: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)
//   }
Copy after login
Copy after login

我们还可以通过字段串形式的日期数据返回间隔对象,比如:

// 从日期语句创建时间间隔
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)
//   }
Copy after login
Copy after login

此外,在获得对象后进行输出的时候,DateInterval 对象也为我们提供了一个 format() 方法,可以像 printf() 函数一样来格式化地输出日期信息,而且这里用的格式符还是日期的格式符。

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

输出的内容其实就是属性中对应的那些日期和时间差值。

时间周期相关函数

说完时间间隔了,我们再来看看时间周期。时间周期是个什么概念呢?就比如说我们要每三天间隔一次地获取日期,这时就可以用时间周期相关的类来进行处理。

$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
Copy after login
Copy after login

首先设定了开始时间和结束时间以及一个时间间隔对象,然后用它们做为参数来生成一个 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"
//   }
Copy after login
Copy after login

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

$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)
Copy after login
Copy after login

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

总结

今天学习的内容不知道大家有没有接触过,反正我是只用过 diff() 方法来处理过日期之间的差值问题,而且也并没有注意到过它返回的这个对象具体的内容。而另外两个对象则是压根没有印象,完全就是没听说过的感觉。所以说,平常多刷刷手册还是非常有帮助的,今天学习的内容又让我们知道了很多东西,而且 DatePeriod 在具体的业务实现中是肯定会有使用场景的。学习不止,后面我们要学习的内容依然精彩。

测试代码:
https://github.com/zhangyue0503/dev-blog/blob/master/php/202009/source/12.PHP中的日期相关函数(一).php
参考文档:
https://www.php.net/manual/zh/book.datetime.php
Copy after login

推荐学习:php视频教程

The above is the detailed content of Introduction to PHP date-related functions (1). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template