PHP, use strtotime to subtract minutes from a date-time variable?

不羁的心 提交于 2019-11-27 15:57:15

问题


I need to subtract 45 minutes from the date-time variable in PHP.

The code:

$thestime = '2012-07-27 20:40';
$datetime_from = date("Y-m-d h:i",strtotime("-45 minutes",strtotime($thestime)));
echo $datetime_from;

returns the result 2012-07-27 07:55.

It should be 2012-07-27 19:55, though. How do I fix this?


回答1:


You should do:

$datetime_from = date("Y-m-d H:i", strtotime("-45 minutes", strtotime($thestime)));

Having H instead of h means a 24-hour format is used, representing the hour with leading zeros: 00 through 23.

You can read more on this in the PHP date function documentation.


There are also object oriented ways of doing this which are more fluent, like DateTime::sub:

$datetime_from = (new DateTime($thestime))->sub(DateInterval::createFromDateString('45 minutes'))->format('Y-m-d H:i')

Or the even more expressive way offered by the Carbon library which extends PHP's built in DateTime class:

$datetime_from = (new Carbon($thestime))->subMinutes(45)->format('Y-m-d H:i');


来源:https://stackoverflow.com/questions/11688829/php-use-strtotime-to-subtract-minutes-from-a-date-time-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!