0

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

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

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

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

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

在此处输入图像描述

4

4 回答 4

3

使用 PHP 的DateTime类 - 将两个日期实例化为对象DateTimediff在它们之间进行操作。最后,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');
于 2013-01-23T16:46:13.063 回答
2

我只能假设您正在尝试获取天数差异:

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

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

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

$daysDifference将包含天数。

于 2013-01-23T16:45:10.923 回答
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

于 2013-01-23T16:45:41.440 回答
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
于 2013-01-23T16:58:44.183 回答