简体   繁体   English

使用 unix 获取两个日期之间的差异

[英]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:在 json 文件中,我有 unix 日期:

      "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.您在$day上的date_create调用是错误的。 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演示: http://sandbox.onlinephpfunctions.com/code/504afecb72bab656bcaf3be8d95bf7f06f5be845

date_create() receives the date/time string in with one of the specific Date and Time Formats . date_create()接收具有特定日期和时间格式之一的日期/时间字符串。 In your case, you're trying to convert a Unix Timestamp to a DateTime object.在您的情况下,您正在尝试将 Unix 时间戳转换为 DateTime object。 You can do that properly by replacing the following line:您可以通过替换以下行来正确执行此操作:

$datetime1 = date_create('$day');

with:和:

$datetime1 = date_create('@'.$day);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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