【问题标题】:find files modified between two dates using php使用php查找在两个日期之间修改的文件
【发布时间】:2014-06-06 14:45:26
【问题描述】:

我对 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 上循环遍历这个数组,但这是将来要做的事情,但它的日期和日期时间的混合让我感到困惑。

【问题讨论】:

    标签: php date datetime filemtime


    【解决方案1】:

    您不会将 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');
    

    它为您提供时间戳,无需进一步转换

    【讨论】:

    • 谢谢。这一切都非常令人困惑。如您所说,为 $yearago 和 $sixmonths 创建的时间戳是 Unix 时间戳,相对于 1970 年 1 月 1 日的秒数?
    【解决方案2】:

    您可以使用strtotime 函数根据人类时间表示生成时间戳(例如1 year ago)。

    现在你可以像这样使用它了:

    <?php
    
    // Load Timestamps
    $sixMonthsAgo = strtotime("6 months ago");
    $oneYearAgo = strtotime("1 year ago");
    
    // Load Files & Check Timestamps
    // Note* you can filter by ext, e.g: /datacore/*.pdf
    $myFiles = glob("/datacore/*");
    
    // Now Check & Build List
    $checkedFiles = array();
    foreach ($myFiles as $myFile) {
        $fileModifiedTime = filemtime($myFile);
        if ($fileModifiedTime >= $oneYearAgo && $fileModifiedTime <= $sixMonthsAgo)
            $checkedFiles[] = $myFile;
    }
    
    // Debug
    echo "Found ". sizeof($checkedFiles) ." files that were updated from ". 
         date('d-m-Y H:i:s a', $sixMonthsAgo) ." to ". 
         date('d-m-Y H:i:s a', $oneYearAgo);
    
    echo "<pre>";
    print_r($checkedFiles);
    echo "</pre>";
    

    【讨论】:

      【解决方案3】:

      GitHub上有一个项目名为:ZFYL zipper

      如果您将其部署在您的服务器上,请将 Directory 更改为 zip,并将模式更改为 JUST SHOW ZIPPABLE FILES LIST

      节目截图:

      ZFYL zipper mainpage

      此外,如果需要,您可以将 zipper.php 包含到任何 php 文件中并调用内置函数。

      GitHub wiki 页面 (github.com/ZFYL/zipper/wiki/Functions) 中描述了如何使用该库。

      【讨论】:

        猜你喜欢
        • 2014-10-19
        • 2021-04-10
        • 2020-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-04
        • 1970-01-01
        相关资源
        最近更新 更多