如何使用PHP处理日期和时间?

Nor*_*ld2 5 php time datetime date

我需要使用PHP的MySQL数据库中的时间和日期值进行更复杂的计算.

我需要添加或减去给定日期的不同值.

例如:

  • 减少1个月
  • 减少30天
  • 减去4周
  • 添加4个月
  • 添加3个月
  • 添加90天
  • 增加2年

请注意,减去1个月,4个星期或30天之间存在差异.

这样做的首选方式是什么?有没有聪明的库或者我可以用PHP自己的功能吗?

dre*_*rew 7

来自http://php.net/manual/en/function.strtotime.php

<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>
Run Code Online (Sandbox Code Playgroud)

您可以添加第二个参数以使其添加到给定时间:

echo strtotime("+1 week",$timestamp)
Run Code Online (Sandbox Code Playgroud)


Bry*_* M. 5

您可以使用PHP5 DateTimeDateInterval对象的组合.

$now = new DateTime();

// 30 days ago
$now->sub(new DateInterval("P30D");

// 1 week ago
$now->sub(new DateInterval("P1W");

// 2 years from now
$now->add(new DateInterval("P1Y");
Run Code Online (Sandbox Code Playgroud)

有关间隔代码列表,请参阅手册


Nic*_*erd 0

检查一下strtotime()功能。http://php.net/manual/en/function.strtotime.php

另请注意,您可以使用第二个参数来指示何时开始。

strtotime('+1 day', mktime(0, 0, 0, 7, 1, 2000));
Run Code Online (Sandbox Code Playgroud)