我尝试比较两个日期并返回结果。 如果文件超过2天,则回显。 这是我的代码:
$filename = './Sample.htm';
$filedate = date('d/m/Y H:i:s', filemtime($filename));
$date = new DateTime('-2 days');
$noData = '';
if ($filedate > $date->format('d/m/Y H:i:s')) {
$Data = "<p>The file is created in the last 2 days!</p>";
} else {
$Data = "<p>The file is older than 2 days</p>";
}
echo $Data;
只有在同一个月范围内进行比较时,代码才有效。如果文件是在另一个月,它不起作用。有什么想法吗?
答案 0 :(得分:1)
filemtime
returns “a Unix timestamp”未经修改。如果您与$date->format('U')
进行比较,您将会有更轻松的时间。
$filename = './Sample.htm';
$fileAge = filemtime($filename);
$twoDaysAgo = new DateTime('-2 days');
$noData = '';
if ($fileAge > $twoDaysAgo->format('U')) {
$Data = "<p>The file is created in the last 2 days!</p>";
} else {
$Data = "<p>The file is older than 2 days</p>";
}
echo $Data;
或,将两者转换为DateTime
个对象然后进行比较。