如何将两个unixtime日期之间的差异转换为天?

时间:2013-01-23 16:38:56

标签: php unix-timestamp

我正在尝试确定目录中文件的日期与当前日期之间的差异,我尝试计算两种方式:

 $fileUnixTimeDate = filemtime($file);
 $fileFormattedDate = date('m/d/y',filemtime($file));

 $todayUnixTimeDate =  time();
 $todayFormattedDate = date('m/d/y',time());

 $unixDifference = $todayUnixTimeDate - $fileUnixTimeDate;
 $formattedDifference =  $todayFormattedDate - $fileFormattedDate;

这是目录中两个文件的结果:

enter image description here

4 个答案:

答案 0 :(得分:3)

使用PHP的DateTime类 - 将两个日期实例化为DateTime的对象,并在它们之间执行diff。最后,format diff输出日期值。

使用http://php.net/DateTime作为参考。

编辑:示例:

$dt1 = new DateTime(date('Y-m-d H:i:s', filemtime($file)));
$dt2 = new DateTime(); // this would be the "now" datetime

$diff = $dt1->diff($dt2);

echo $diff->format('%R%a days');

答案 1 :(得分:2)

我只能假设你试图获得天数的差异:

$fileUnixTimeDate = filemtime($file);
$todayUnixTimeDate =  time();

$unixDifference = $todayUnixTimeDate - $fileUnixTimeDate;
$daysDifference = $unixDifference/86400;

注意: 86400,因为1天内有86400秒。

$daysDifference将包含天数。

答案 2 :(得分:0)

unix时间计算已经是一个很好的开始:

$fileUnixTimeDate = filemtime($file);
$todayUnixTimeDate =  time();
$unixDifference = $todayUnixTimeDate - $fileUnixTimeDate;

现在有了给定的结果(7389045& 7216242),您需要将它们转换为可读格式。例如,7389045~ = 85.5天。 7216242~ = 83.5天

echo "Hours difference = ".floor((unixDifference )/3600) . "<br>";
echo "Minutes difference = ".floor((unixDifference )/60) . "<br>";
echo "Seconds difference = " .(unixDifference ). "<br>";
echo "Days difference = ".floor((unixDifference )/86400) . "<br>";

试一试,看看你得到了什么结果。

请参阅此问题:Finding days between 2 unix timestamps in php

更多关于Unix时间:http://en.wikipedia.org/wiki/Unix_time

答案 3 :(得分:0)

使用DateTime类可以很容易地处理日期:

// Pretend this is from "filemtime()"
$time = strtotime('9 days ago');

// Create a DateTime object using the file's creation time
// Note: Unix timestamps need to be prefixed with "@"
$filetime = new \DateTime('@'.$time);

// The datetime right now, for comparison
$now = new \DateTime('now');

// Get the difference between the two times
$diff = $filetime->diff($now);

// And echo out the day difference
echo "The file was created {$diff->days} days ago.";

$diff变量包含许多好东西:

object(DateInterval)[3]
    public 'y' => int 0
    public 'm' => int 0
    public 'd' => int 9
    public 'h' => int 0
    public 'i' => int 0
    public 's' => int 0
    public 'invert' => int 0
    public 'days' => int 9