DataTime类跟date(),strtotime(),gmdate()等函数有相同的作用,都是用来处理日期和时间的,但DateTime类更加直观、方便, 所以在PHP5.2.0以后推荐使用DateTime类而不是相应的函数。

下面来看一下DateTime类的用法。

1. 获取当前系统时间并打印

<?php
$date = new DateTime();
echo $date->format('Y-m-d H:i:s');
?>

执行结果为:2014-08-25 12:58:29

2. 获取特定时间并打印

<?php
$date = new DateTime('2014-05-04');
echo $date->format('Y-m-d H:i:s');
echo "\n";
$date2 = new DateTime('tomorrow');
echo $date2->format('Y-m-d H:i:s');
echo "\n";
$date2 = new DateTime('+2 days');
echo $date2->format('Y-m-d H:i:s');
?>

执行结果为: 2014-05-04 00:00:00 2014-08-26 00:00:00 2014-08-27 13:13:34

或则通过DateTime的其他方法

<?php
$date = new DateTime();
// add方法
$date->add(new DateInterval('P1D'));
echo $date->format('Y-m-d H:i:s');
echo "\n";
// modify方法
$date->modify('+1 day');
echo $date->format('Y-m-d H:i:s');
echo "\n";
// setDate方法
$date->setDate('1989-11-10');
echo $date->format('Y-m-d H:i:s');
echo "\n";
// setTime方法
$date->setTime('11:10:10');
echo $date->format('Y-m-d H:i:s');
echo "\n";
?>

执行结果分别为: 2014-08-26 15:02:57 2014-08-27 15:02:57 1989-11-10 15:02:57 1989-11-10 11:10:10

3. unix时间戳的转换

获取当前时间的时间戳

<?php
$date = new DateTime();
echo $date->format('U');
echo "\n";
?>

执行结果为:1408950651

或者

<?php
$date = new DateTime();
echo $date->getTimestamp();
echo "\n";
?>

将时间戳转换为可读时间

<?php
$date = new DateTime('@1408950651');
$date->setTimezone(new DateTimeZone('Asia/Shanghai'));
echo $date->format('Y-m-d H:i:s');
echo "\n";
?>

执行结果为:2014-08-25 15:10:51

或者

<?php
$date = new DateTime();
$date->setTimestamp(1408950651);
echo $date->format('Y-m-d H:i:s');
echo "\n";
?>

4. 日期的比较

日期大小比较

<?php
$date1 = new DateTime();
$date2 = new DateTime('2014-09-15');

if($date1 < $date2) {
    echo $date2->format('Y-m-d H:i:s') . ' is in the future';
}
?>

日期间隔

<?php
$date1 = new DateTime();
$date2 = new DateTime('2014-09-15');

$diff = $date1->diff($date2);
print_r($diff);
?>

执行结果为: DateInterval Object ( [y] => 0 [m] => 0 [d] => 20 [h] => 7 [i] => 35 [s] => 50 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 20 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )

将返回的对象格式化输出

<?php
$date1 = new DateTime();
$date2 = new DateTime('2014-09-15');

$diff = $date1->diff($date2);
echo $diff->format("The future will come in %Y years %m months and %d days");
?>

输出结果为:The future will come in 00 years 0 months and 20 days