【问题标题】:PHP, use strtotime to subtract minutes from a date-time variable?PHP,使用 strtotime 从日期时间变量中减去分钟?
【发布时间】:2012-07-26 04:37:16
【问题描述】:

我需要从 PHP 中的日期时间变量中减去 45 分钟。

代码:

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

返回结果2012-07-27 07:55

不过应该​​是2012-07-27 19:55。我该如何解决这个问题?

【问题讨论】:

    标签: php strtotime


    【解决方案1】:

    你应该这样做:

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

    使用H 代替h 表示使用24 小时格式,表示带有前导零的小时:0023

    您可以在PHP date function documentation 中了解更多信息。


    还有一些更流畅的面向对象的方法,比如DateTime::sub

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

    或者由 Carbon 库提供的更具表现力的方式,它扩展了 PHP 内置的 DateTime 类:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      相关资源
      最近更新 更多