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 使用yolov5-7.0目标检测报错
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备