我需要使用PHP的MySQL数据库中的时间和日期值进行更复杂的计算。
我需要添加或减去给定日期的不同值。
例如:
请注意,减去1个月,4个星期或30天之间存在差异。
这样做的首选方法是什么?有没有聪明的库,或者我可以使用PHP自己的函数吗?
答案 0 :(得分: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";
?>
您可以添加第二个参数以使其添加到给定时间:
echo strtotime("+1 week",$timestamp)
答案 1 :(得分:5)
您可以结合使用PHP5的DateTime
和DateInterval
个对象。
$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");
有关区间代码的列表,请参阅the manual
答案 2 :(得分:4)
从PHP 5.2开始,您拥有DateTime对象。 你可以这样做:
$date = new DateTime; // now
$date->modify('1 month ago');
echo $date->format('Y-m-d');
检查this link是否有完整的sintax。
答案 3 :(得分:1)
PHP函数strtotime在这方面非常强大。
例如:
// 1 month ago
$date = strtotime('-1 month');
// 30 days ago
$date = strototime('-30 days');
答案 4 :(得分:1)
<?php
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>
$ date现在是'2000-01-11'。
您还可以使用date_sub
减去一段时间。
更多信息:
http://www.php.net/manual/en/datetime.add.php http://www.php.net/manual/en/datetime.sub.php
答案 5 :(得分:0)
查看strtotime()
功能。 http://php.net/manual/en/function.strtotime.php
另请注意,您可以使用第二个参数来指示何时开始。
strtotime('+1 day', mktime(0, 0, 0, 7, 1, 2000));
答案 6 :(得分:0)
尝试Pear Date库。非常强大和灵活,具有周期添加功能。它完全符合您的要求。
我们在日期密集的Web应用程序中使用它,我们必须添加大量时间变量周期并计算周数等。
答案 7 :(得分:0)
请查看此PHP dates
答案 8 :(得分:0)
根据您的应用程序,您将要使用mysql日期时间函数
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add
或strtotime就像其他人一样说过
答案 9 :(得分:0)
这是另一个建议。如果你想操纵mysql中的信息,请尝试使用mysql here提供的日期/时间函数