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条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历