## 使用[DateTime 類](http://www.php.net/manual/en/class.datetime.php)。
在 PHP 糟糕的老時光里,我們必須使用?[date()](http://www.php.net/manual/en/function.date.php),?[gmdate()](http://www.php.net/manual/en/function.gmdate.php),?[date_timezone_set()](http://www.php.net/manual/en/function.date-timezone-set.php),?[strtotime()](http://www.php.net/manual/en/function.strtotime.php)等等令人迷惑的 組合來處理日期和時間。悲哀的是現在你仍舊會找到很多在線教程在講述這些不易使用的老式函數。
幸運的是,我們正在討論的 PHP 版本包含友好得多的?[DateTime 類](http://www.php.net/manual/en/class.datetime.php)。 該類封裝了老式日期函數所有功能,甚至更多,在一個易于使用的類中,并且使得時區轉換更加容易。 在PHP中始終使用 DateTime 類來創建,比較,改變以及展示日期。
## 示例
~~~
<?php
// Construct a new UTC date. Always specify UTC unless you really know what you're doing!
$date = new DateTime('2011-05-04 05:00:00', new DateTimeZone('UTC'));
// Add ten days to our initial date
$date->add(new DateInterval('P10D'));
echo($date->format('Y-m-d h:i:s')); // 2011-05-14 05:00:00
// Sadly we don't have a Middle Earth timezone
// Convert our UTC date to the PST (or PDT, depending) time zone
$date->setTimezone(new DateTimeZone('America/Los_Angeles'));
// Note that if you run this line yourself, it might differ by an hour depending on daylight savings
echo($date->format('Y-m-d h:i:s')); // 2011-05-13 10:00:00
$later = new DateTime('2012-05-20', new DateTimeZone('UTC'));
// Compare two dates
if($date < $later)
echo('Yup, you can compare dates using these easy operators!');
// Find the difference between two dates
$difference = $date->diff($later);
echo('The 2nd date is ' . $difference['days'] . ' later than 1st date.');
?>
~~~
## 陷阱
* 如果你不指定一個時區,[DateTime::__construct()](http://www.php.net/manual/en/datetime.construct.php)?就會將生成日期的時區設置為正在運行的計算機的時區。之后,這會導致大量令人頭疼的事情。?**在創建新日期時始終指定 UTC 時區,除非你確實清楚自己在做的事情。**
* 如果你在 DateTime::__construct() 中使用 Unix 時間戳,那么時區將始終設置為 UTC 而不管第二個參數你指定了什么。
* 向 DateTime::__construct() 傳遞零值日期(如:“0000-00-00”,常見 MySQL 生成該值作為 DateTime 類型數據列的默認值)會產生一個無意義的日期,而不是“0000-00-00”。
* 在 32 位系統上使用?[DateTime::getTimestamp()](http://www.php.net/manual/en/datetime.gettimestamp.php)?不會產生代表 2038 年之后日期的時間戳。64 位系統則沒有問題。
## 進一步閱讀
* [PHP 手冊:DateTime 類](http://www.php.net/manual/en/book.datetime.php)
* [Stack Overflow: 訪問超出 2038 的日期](http://stackoverflow.com/questions/5319710/accessing-dates-in-php-beyond-2038)