1

I have an issue.I need to calculate the time difference but here the date_create function is not showing any output in php.I am explaining my code below.

while($row=mysqli_fetch_assoc($orderqry)){
    $exit_date=$row['delivered_datetime'];
    if($exit_date!=='0000-00-00 00:00:00'){  
       $deldate=date_create($exit_date);
       $today=date_create(date('Y-m-d H:i:s'));
      echo $today;exit;
      $interval = date_diff($deldate, $today);
      $hours = $interval->format('%h');    
}
}

Here i am trying to echo $today but its not giving any result.Here i need to calculate the time difference in hour.In my DB i have existing time in the format of date('Y-m-d H:i:s').Please help me.

4
  • "Returns new DateTime object." You'll need to format it to display or compare. Commented Mar 17, 2016 at 3:53
  • date_create return an instance of DateTime not a string, you have to use $today->format('Y-m-d H:i:s'); if you want to echo the result Commented Mar 17, 2016 at 3:55
  • 1
    echo $today cause an error. echo $hours; it's ok. Please note that %h doesn't return total hours, it return only values 0-23. To obtain total value you have to write $hours = $interval->h + ($interval->days*24); Commented Mar 17, 2016 at 4:21
  • Calling date_create() without parameter is same as creating DateTime with current date time. So $today=date_create(date('Y-m-d H:i:s')); will have same output as $today=date_create(); Commented Mar 17, 2016 at 5:37

2 Answers 2

1

$today is DateTime instance. To echo it you need to call its format() method.

echo $today->format('Y-m-d H:i:s');
Sign up to request clarification or add additional context in comments.

4 Comments

How can i extract the time interval.
You have done it $hours = $interval->format('%h');
i am trying to echo $hours but its not coming.
Are you sure? echo $hours; should be ok.
0

date_create is an alias of: DateTime::__construct(). see below example, I have assigned 6 Hour ago date in $exit_date. so ideally difference from current date should be 6 Hour.

$exit_date = date('Y-m-d H:i:s', strtotime('-6 Hours'));
$deldate=date_create($exit_date); //returns datetime class object
$today=date_create(date('Y-m-d H:i:s'));

$interval = date_diff($deldate, $today);
echo $hours = $interval->format('%h'); // output 6 hours

If you want to print date from $today variable then use:

echo $today->format('Y-m-d H:i:s'); //output: today's date in Y-m-d H:i:s format

for more detail have a look at http://php.net/manual/en/book.datetime.php

Comments

Your Answer

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