1

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

4

3 回答 3

1

您不会将 date_sub 值分配回变量,因此“减去”的值会丢失。你应该有:

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

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

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

注意$yearagoand$sixmonths是 DateTime 对象,whilefilemtime()返回标准的 Unix 时间戳,你不能直接比较它们。

所以你也可以

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

这为您提供了开始的时间戳,无需进一步转换

于 2014-06-06T14:52:44.940 回答
0

您可以使用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>";
于 2014-06-06T14:55:59.820 回答
-1

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

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

节目截图:

ZFYL拉链主页

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

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

于 2017-08-18T09:37:33.710 回答