我对php中的各种日期函数和格式感到非常困惑,因此,如果可能,我想寻求帮助。
我正在尝试查找在两个日期之间修改过的文件,但是语法使我感到困惑。例如,如果我尝试查找在6个月至1年前之间更改过的文件,则可以尝试:
$yearago = new DateTime("now");
date_sub($yearago, date_interval_create_from_date_string("1 year"));
$sixmonthsago = new DateTime("now");
date_sub($sixmonthsago, date_interval_create_from_date_string("6 months"));
$dir = '/datacore/';
$files1 = scandir($dir);
foreach($files1 as $key => $value)
{
$datemod = filemtime($value);
if ($datemod>$yearago && $datemod<$sixmonthsago) // eg between 6 and 12 months ago
{
// Do stuff
}
}
我知道这是低效的;在目录中找到文件名数组,然后在filemtime上遍历此数组,但这在将来会做一些事情,但是日期和DateTime的混合让我感到困惑。
您无需将date_sub值分配回变量,因此“减去”后的值会丢失。您应该有:
$yearago = date_sub($yearago, ...);
另外,您可以简单地告诉DateTime生成以以下内容开头的正确日期:
$yearago = new DateTime("1 year ago");
$sixmonths = new DateTime('6 months ago');
请注意,$yearago
和$sixmonths
是DateTime对象,虽然filemtime()
返回标准的Unix时间戳,但是您不能直接比较它们。
因此,您不妨拥有
$yearago = strtotime('1 year ago');
$sixmonths = strtotime('6 months ago');
这为您提供了时间戳记,无需进一步转换
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句