简体   繁体   中英

Get difference between 2 dates with unix

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');
?>

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.

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM