0

WHAT I AM DOING

I want to find the difference between 2 datetime and add it to another datetime. I am only able to get the difference in Y-m-d H:i:s format.

CODE

    $begin = new DateTime($start);
    $finish =  new DateTime($end);
    $diff = $begin->diff($finish);
    $difference = $diff->format("%Y-%M-%D %H:%I:%S");

Here I want to add $difference to another datetime say $finaldate. If its not possible is there any way of getting the difference in only minutes, then i could use $date->modify("+$difference minutes");

2
  • 1
    convert to time stamp using strtotime calculate difference (gives it in an int) add int to final time stamp convert time stamp back to y-m-d h:i:s Commented Jun 25, 2013 at 12:52
  • Would appreciate if its possible using DateTime Commented Jun 25, 2013 at 12:55

2 Answers 2

1

*This is a method using DateTime:*

$begin = new DateTime($start);
$finish =  new DateTime($end);


$difference = $finish->format('U') - $begin->format('U');

// working version
$minutesDiff = round(($difference/60), 0);
$finalDate = new DateTime();
$finalDate->modify(sprintf('+%s minutes', $minutesDiff));

edit added missing bracket

edit2 version without ->diff() method

Sign up to request clarification or add additional context in comments.

8 Comments

can you provide an answer with how to obtain difference in minutes.
the new version should work with minutes, but it depends if you want the seconds completely removed or rounded
@gries: not working. I gave 2 datetimes 2013-06-26 03:00 and 2013-06-26 04:00. it returns 0.
@Avinash plz provide your full code, this code is working, also 03:00 vs. 04:00 is a difference of 1 hour. btw. what is "returning 0" ? which variable has the value 0?
@gries: I am also facing the same problem. I think its because %s gives only the seconds part of the datetime and hence $minutesDiff is returning 0
|
0

What about:

$begin = strtotime($start);
$finish= strtotime($end);
$diff  = $finish-$begin;
$finaldate = strtotime($finaldate)+$diff;
echo date("Y-M-D h-i-s",$finaldate);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.