当前位置: 首页>>编程语言>>正文


PHP处理日期和时间

本文摘译整理自PHP最佳实践-PHP处理日期和时间。

使用DateTime 类。

在 PHP 糟糕的老时光里,我们必须使用 date(), gmdate(), date_timezone_set(), strtotime()等等令人迷惑的 组合来处理日期和时间。悲哀的是现在你仍旧会找到很多在线教程在讲述这些不易使用的老式函数。

幸运的是,我们正在讨论的 PHP 版本包含友好得多的 DateTime 类。 该类封装了老式日期函数所有功能,甚至更多,在一个易于使用的类中,并且使得时区转换更加容易。 在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() 就会将生成日期的时区设置为正在运行的计算机的时区。之后,这会导致大量令人头疼的事情。 在创建新日期时始终指定 UTC 时区,除非你确实清楚自己在做的事情。
  • 如果你在 DateTime::__construct() 中使用 Unix 时间戳,那么时区将始终设置为 UTC 而不管第二个参数你指定了什么。
  • 向 DateTime::__construct() 传递零值日期(如:“0000-00-00”,常见 MySQL 生成该值作为 DateTime 类型数据列的默认值)会产生一个无意义的日期,而不是“0000-00-00”。
  • 在 32 位系统上使用 DateTime::getTimestamp() 不会产生代表 2038 年之后日期的时间戳。64 位系统则没有问题。

进一步阅读

本文由《纯净天空》出品。文章地址: https://vimsky.com/article/1726.html,未经允许,请勿转载。