如何使用PHP处理日期和时间?
我需要使用PHP对MySQL数据库中的时间和日期值进行更复杂的计算 我需要从给定日期添加或减去不同的值 例如:如何使用PHP处理日期和时间?,php,date,datetime,time,Php,Date,Datetime,Time,我需要使用PHP对MySQL数据库中的时间和日期值进行更复杂的计算 我需要从给定日期添加或减去不同的值 例如: // 1 month ago $date = strtotime('-1 month'); // 30 days ago $date = strototime('-30 days'); 减去1个月 减去30天 减去4周 增加4个月 增加3个月 增加90天 增加2年 请注意,减去1个月、4周或30天之间存在差异 这样做的首选方式是什么?有没有聪明的库,或者我可以用PHP自己的函数
// 1 month ago
$date = strtotime('-1 month');
// 30 days ago
$date = strototime('-30 days');
- 减去1个月
- 减去30天
- 减去4周
- 增加4个月
- 增加3个月
- 增加90天
- 增加2年
这样做的首选方式是什么?有没有聪明的库,或者我可以用PHP自己的函数来实现这一点?查看
strotime()
函数
还请注意,您可以使用第二个参数指示何时开始
strtotime('+1 day', mktime(0, 0, 0, 7, 1, 2000));
从
PHP函数在这方面非常强大
例如:
// 1 month ago
$date = strtotime('-1 month');
// 30 days ago
$date = strototime('-30 days');
试试梨枣库。非常强大和灵活,具有周期添加功能。这正是你想要的 我们在一个日期非常密集的web应用程序中使用它,在这个应用程序中,我们必须添加许多时间可变的时段,并计算周数等。请看这个
$date现在将是'2000-01-11'
您还可以使用date\u sub
减去时间量
详情如下:
http://www.php.net/manual/en/datetime.sub.php根据您的应用程序,您需要使用mysql日期时间函数或
或者像其他人所说的那样,您可以使用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");
有关间隔代码的列表,请参见另一个建议。如果您想从mysql操作信息,请尝试使用mysql提供的日期/时间函数,因为PHP5.2提供了DateTime对象。 你可以做:
$date = new DateTime; // now
$date->modify('1 month ago');
echo $date->format('Y-m-d');
检查完整的sintax。+1但请注意,这仅适用于php5.3->您可以在5.2中使用DateTime的modify()方法
$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");
$date = new DateTime; // now
$date->modify('1 month ago');
echo $date->format('Y-m-d');