DevGe
DevGe

Reputation: 1449

How to fix not accurate the two datetime using php

I have question regarding to my module, I found out that my the two date and time is not accurate well, The first date time has a value however the second has no value, so if that is the case, the result will be null or i't can't show any value in my table data.

To demonstrate well, I will show you guys the sample output that I already coded.

Output

$datetime1 = new DateTime($res_parent->created_store1);
$datetime2 = new DateTime($res_parent->arl_approved);
$interval = $datetime1->diff($datetime2);

$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');

In my database output it look like this,

output

Upvotes: 1

Views: 58

Answers (1)

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4577

Assuming the values of $res_parent are correct, there is nothing wrong with the above code, although you may want to check if the dates are set before performing operations on the dates, and set a default string if the date values are not available:

if(!empty($res_parent->arl_approved) && !empty($res_parent->created_store1){
  $datetime1 = new DateTime('2019-04-11 16:20:03');
  $datetime2 = new DateTime('2019-04-11 16:19:30');
  $interval = $datetime1->diff($datetime2);
  $elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
}else{
  $elapsed = "Not Available";
}

Gives us the result:

"0 years 0 months 0 days 0 hours 0 minutes 33 seconds"

Or

"Not Available"

Please check and ensure your $res_parent object is set correctly.

Hope that helps,

Upvotes: 1

Related Questions