PHP,使用 strtotime 从日期时间变量中减去分钟?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11688829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP, use strtotime to subtract minutes from a date-time variable?
提问by Klausos Klausos
I need to subtract 45 minutes from the date-time variable in PHP.
我需要从 PHP 中的日期时间变量中减去 45 分钟。
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.
返回结果2012-07-27 07:55。
It should be 2012-07-27 19:55, though. How do I fix this?
2012-07-27 19:55不过应该是的。我该如何解决?
回答by Bogdan
You should do:
你应该做:
$datetime_from = date("Y-m-d H:i", strtotime("-45 minutes", strtotime($thestime)));
Having Hinstead of hmeans a 24-hour format is used, representing the hour with leading zeros: 00through 23.
有H而不是h意味着使用 24 小时格式,用前导零表示小时:00到23。
You can read more on this in the PHP date function documentation.
您可以在PHP 日期函数文档中阅读更多相关内容。
There are also object oriented ways of doing this which are more fluent, like DateTime::sub:
还有一些面向对象的方法可以更流畅地执行此操作,例如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 Carbonlibrary which extends PHP's built in DateTimeclass:
或者Carbon扩展 PHP 内置DateTime类的库提供的更具表现力的方式:
$datetime_from = (new Carbon($thestime))->subMinutes(45)->format('Y-m-d H:i');

