ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
## 使用[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)