stkmedia
stkmedia

Reputation: 159

php datetime difference between datetime and datetime+int days

Trying to use the datetime in database and add a variable amount of days to it, then find the difference between the old date and new date and display it. I've reference http://php.net/manual/en/datetime.add.php and

$postdate = $row["dated"]; // db value(datetime) assume 2016-04-12 18:35:00
$timelength = $row["timelength"]; // db value(int) assume 180
//Start decode and organizing
$time1 = new DateTime($postdate);
$time111 = date_add($time1, date_interval_create_from_date_string(''.$timelength.' days'));
$time211 = $time111->diff($time1);
$time222 = $time211->format('%d days %h hours %i minutes');

$time222 echo output is 0 days 0 hours 0 minutes

It should be 170 days ## hours ## minutes I tried several approaches from the manual, Please don't ban me from SO.

Upvotes: 0

Views: 93

Answers (1)

Mark Baker
Mark Baker

Reputation: 212452

$time111 = date_add($time1, ...);

changes $time1 to the new value as well as assigning it to $time111

Instead, do

$time1 = new DateTime($postdate);
$time2 = clone $time1;
$time111 = date_add($time2, date_interval_create_from_date_string(''.$timelength.' days'));

Upvotes: 4

Related Questions