douyulv6921 2014-12-03 21:03
浏览 66
已采纳

在PHP中减去日期不起作用

I have a litle problem with a substraction of dates in PHP, here is one of the many codes that I tried :

date_default_timezone_set('Europe/Paris');
$log_end = new DateTime(); // date from which I want to substract a period
$log_begin = $log_end->sub(new DateInterval('PT0H1M2S')); //I substract the period to the date to find the when the log begins.
$log_b = $log_begin->format("Y-m-d H:i:s");
$log_e = $log_end->format("Y-m-d H:i:s");
print_r($log_b);
print_r("
");
print_r($log_e);

Here is what is printed :

2014-12-03 21:50:41
2014-12-03 21:50:41

As you can see, the dates are the same, whatever methods I used, the result was the same. So did I made a mistake somewhere or what I want do is impossible ?

Thank you in advance for taking the time to help me and answer me, let me know if you need informations.

  • 写回答

2条回答 默认 最新

  • doukanwa6872 2014-12-03 21:08
    关注
    $log_begin = $log_end->sub(new DateInterval('PT0H1M2S')); 
    

    Subtracts the dateinterval from $log_end (so $log_end is now 2014-12-03 21:50:41) and returns a new DateTime object with the same (2014-12-03 21:50:41) value that is stored in $log_begin

    To prevent $log_end from being adjusted, clone it to $log_begin and then subtract the period from $log_begin

    date_default_timezone_set('Europe/Paris');
    $log_end = new DateTime(); // date from which I want to substract a period
    $log_begin = clone $log_end;
    $log_begin->sub(new DateInterval('PT0H1M2S')); //I substract the period to the date to find the when the log begins.
    $log_b = $log_begin->format("Y-m-d H:i:s");
    $log_e = $log_end->format("Y-m-d H:i:s");
    print_r($log_b);
    print_r("
    ");
    print_r($log_e);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘