作者:吴为36 | 来源:互联网 | 2023-07-09 09:55
篇首语:本文由编程笔记#小编为大家整理,主要介绍了php日期相关的类DateIntervalDateTimeZoneDatePeriod相关的知识,希望对你有一定的参考价值。
篇首语:本文由编程笔记#小编为大家整理,主要介绍了php 日期相关的类 DateInterval DateTimeZone DatePeriod相关的知识,希望对你有一定的参考价值。
* DateInterval
php
/**
* Created by PhpStorm.
* User: Mch
* Date: 7/18/18
* Time: 21:30
*/
$datetime = new DateTime(‘2018-07-18 21:30:00‘);
// +2 weeks
$interval = new DateInterval(‘P2W‘);
$datetime->add($interval);
echo $datetime->format(‘Y-m-d H:i:s‘).PHP_EOL;
// + 1month
$datetime->add(
new DateInterval(‘P1M‘)
);
echo $datetime->format(‘Y-m-d H:i:s‘).PHP_EOL;
// -1month -2weeks
$datetime->add(
DateInterval::createFromDateString("-1 month -2 weeks")
);
echo $datetime->format(‘Y-m-d H:i:s‘).PHP_EOL;
echo ‘------------------‘,PHP_EOL;
// start, interval, recurrences
$datePeriod = new DatePeriod(
$datetime,
DateInterval::createFromDateString(‘-1 day‘),
3
);
foreach ($datePeriod as $date) {
echo $date->format(‘Y-m-d‘),PHP_EOL;
}
output:
2018-08-01 21:30:00
2018-09-01 21:30:00
2018-07-18 21:30:00
------------------
2018-07-18
2018-07-17
2018-07-16
2018-07-15
* DateTimeZone
/**
* Created by PhpStorm.
* User: Mch
* Date: 7/18/18
* Time: 21:42
*/
$timezOne= new DateTimeZone(‘Asia/Tokyo‘);
$datetime = new DateTime(‘2018-07-18 22:42:00‘, $timezone);
$datetime->setTimezone(
new DateTimeZone(‘Asia/Shanghai‘)
);
echo $datetime->format(‘Y-m-d H:i:s‘).PHP_EOL;
// 2018-07-18 21:42:00
* DatePeriod
/**
* Created by PhpStorm.
* User: Mch
* Date: 7/18/18
* Time: 21:51
*/
$start = new DateTime();
// $interval = new DateInterval(‘P2W‘);
$interval = new DateInterval(‘P1D‘);
$period = new DatePeriod(
$start,
$interval,
3,
DatePeriod::EXCLUDE_START_DATE
);
foreach ($period as $nextDateTime) {
echo $nextDateTime->format(‘Y-m-d H:i:s‘),PHP_EOL;
}
/**
2018-07-19 15:54:20
2018-07-20 15:54:20
2018-07-21 15:54:20
*/