0

i have to calculate the difference between two date in this format:

Fri, 29 Apr 2016 12:27:29 +0200

But i can't use date_diff() function..how can i do that?

With this code

<?php
    $now = date(DATE_RFC2822);
    $now = date_create($now);
    $feed_date = date_create($feeds[$y-1]); //value of $feeds[$y-1] = Fri, 29 Apr 2016 12:27:29 +0200
    $feed_date = date_diff($now,$feed_date) ?>

I get this:

Catchable fatal error: Object of class DateInterval could not be converted to string in blablabla

[EDIT] it won't work..if i use this i get always 0 minutes

$now = date(DATE_RFC2822);
    $now = date_create($now);
    $feed_date = date_create($feeds[$y-1]);
    $data_post = date_diff($now,$feed_date);
     ?>
      <?php echo $data_post->format('%R%a minutes'); ?>

2 Answers2

2

The date_diff() function accepts DateTime objects and returns a DateInterval object:

$datetime1 = date_create('Fri, 29 Apr 2016 12:27:29 +0200');
$datetime2 = date_create('Sat, 30 Apr 2016 12:27:29 +0200');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');

Note that this is the procedural style, you can also use the object oriented style if you prefer:

$datetime1 = new DateTime('Fri, 29 Apr 2016 12:27:29 +0200');
$datetime2 = new DateTime('Sat, 30 Apr 2016 12:27:29 +0200');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
Jeroen Noten
  • 3,574
  • 1
  • 17
  • 25
  • Catchable fatal error: Object of class DateInterval could not be converted to string in – Giuseppe De Paola Apr 29 '16 at 10:50
  • You should not print `$interval` immediatly, use the `format()` method on the `DateInterval` to format it before printing. http://php.net/manual/en/dateinterval.format.php – Jeroen Noten Apr 29 '16 at 10:53
0

You could just parse the date before using date_diff:

$date1 = date_create("Fri, 22 Apr 2016 12:27:29 +0200");
$date2 = date_create("Fri, 29 Apr 2016 12:27:29 +0200");
$diff  = date_diff($date1, $date2);
Frederik Spang
  • 3,379
  • 1
  • 25
  • 43
  • Catchable fatal error: Object of class DateInterval could not be converted to string in – Giuseppe De Paola Apr 29 '16 at 10:50
  • You should not print `$diff` immediatly, use the `format()` method on the `DateInterval` to format it before printing, e.g. `echo $diff->format('%R%a days');`. http://php.net/manual/en/dateinterval.format.php – Jeroen Noten Apr 29 '16 at 10:54