Search code examples
phpdatedatetimetimestampoperation

Substraction of dates in PHP doesn't work


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("\n");
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.


Solution

  • $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("\n");
    print_r($log_e);