0

Trying to get the difference between last date vs today.

In a json file, i have unix date:

      "lastUpdate": 1568937600,

And i've tried this but with no success.

<?php
$day = $item['lastUpdate'];;
$datetime1 = date_create('$day');
$datetime2 = date_create('now');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a');
?>

3 Answers3

1

Try this:

$datetime1 = new DateTime(date('Y-m-d', $item['lastUpdate'])); //assuming that you have timestamp in the var $item
$datetime2 = new DateTime(date("Y-m-d", strtotime(date("now"))));
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a');

Hope it Helps.

Serghei Leonenco
  • 3,478
  • 2
  • 8
  • 16
0

Your date_create call on $day is wrong. You need to use double quote to render the variable inside. Also you need an @ sign prefix to indicate it to be a timestamp:

<?php
$day = (int) $item['lastUpdate'];
$datetime1 = date_create("@{$day}");
$datetime2 = date_create('now');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a');
?>

Demo: http://sandbox.onlinephpfunctions.com/code/504afecb72bab656bcaf3be8d95bf7f06f5be845

Koala Yeung
  • 7,475
  • 3
  • 30
  • 50
0

date_create() receives the date/time string in with one of the specific Date and Time Formats. In your case, you're trying to convert a Unix Timestamp to a DateTime object. You can do that properly by replacing the following line:

$datetime1 = date_create('$day');

with:

$datetime1 = date_create('@'.$day);
uri2x
  • 3,162
  • 1
  • 11
  • 25