php 日期相关的类 DateInterval DateTimeZone DatePeriod

Posted mingzhanghui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

<?php
/**
 * 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

<?php
/**
 * 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
 */

  

 








以上是关于php 日期相关的类 DateInterval DateTimeZone DatePeriod的主要内容,如果未能解决你的问题,请参考以下文章

iPhoto dateInterval到本地化日期

swift DateInterval

swift DateInterval

swift DateInterval

swift DateInterval

PHP 时间日期处理类