使用php查找两个日期之间的文件 [英] find files modified between two dates using php

查看:127
本文介绍了使用php查找两个日期之间的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对php中的各种日期功能和格式感到困惑,所以如果可能,我想请求帮助。

我试图找到在两个日期之间被修改的文件,但语法令我困惑。例如,如果我试图找到在6个月和1年前更改的文件,我尝试过:

I'm getting thoroughly confused about the various date functions and formats in php so I would like to ask for help if possible.
I'm trying to find files that were modified between two dates but the syntax is confusing me. For instance, if I tried to find files altered between 6 months and 1 year ago, I have tried:

$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的混合使我感到困惑。

I know this is inefficient; finding an array of filenames in the directory and then looping through this array on filemtime but this is something to work on in the future, but its the mix of date and DateTime thats got me confused.

推荐答案

您不会将date_sub值分配给您的变量,所以减去的值就会丢失。你应该有:

You don't assign your date_sub values back to your variables, so the "subtracted" values are simply lost. You should have had:

$yearago = date_sub($yearago,  ...);

另外,您可以简单地告诉DateTime生成正确的日期,以开始:

Plus, you can simply tell DateTime to generate the proper dates to start with:

$yearago = new DateTime("1 year ago");
$sixmonths = new DateTime('6 months ago');

请注意, $ yearago $ sixmonths 是DateTime对象,而 filemtime()返回一个标准的Unix时间戳,你不能直接比较它们。

Note that $yearago and $sixmonths are DateTime objects, while filemtime() returns a standard Unix timestamp, and you cannot compare them directly.

所以你可能只是有

$yearago = strtotime('1 year ago');
$sixmonths = strtotime('6 months ago');

其中给您时间戳开始,无需进一步转换

which gives you timestamps to start with, no further conversion needed

这篇关于使用php查找两个日期之间的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆