简体   繁体   中英

How to get difference of two dates in php and add that difference to third date to obtain another new date?

There are two variables,

$old_start = new DateTime("2020-12-13 14:20");
$old_end = new DateTime("2021-03-25 12:29");

Now take difference of those two dates:

$gap = $old_end->diff($old_start);

Consider third variable:

$new_start = new DateTime("2020-12-27 11:47");

and based upon this $new_start and $gap, I want a new variable $new_end that is something like add some time period in new starting date to obtain new ending date.

You can achieve that as following, you can learn more about the datetime manipulation from this How we can add two date intervals in PHP

$old_start = new DateTime("2020-12-13 14:20");
$old_end = new DateTime("2021-03-25 12:29");

$interval_diff = $old_start->diff($old_end);

$new_start = new DateTime("2020-12-27 11:47");

$new_end = $new_start->add($interval_diff);

print_r($interval_diff);
print_r($new_end);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM