问题
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
}
}
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.
回答1:
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, ...);
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');
Note that $yearago
and $sixmonths
are DateTime objects, while filemtime()
returns a standard Unix timestamp, and you cannot compare them directly.
So you might as well just have
$yearago = strtotime('1 year ago');
$sixmonths = strtotime('6 months ago');
which gives you timestamps to start with, no further conversion needed
回答2:
You can use strtotime
function to generate timestamp from human representation of time (e.g. 1 year ago
).
Now you can use it like this:
<?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:
There is a project on GitHub named: ZFYL zipper
If you deploy it on your server, change the Directory to zip, and change mode to JUST SHOW ZIPPABLE FILES LIST.
A picture from the program:
ZFYL zipper mainpage
Also, if you need, you can include the zipper.php to any php file and call built-in functions.
How to use this library is described on the GitHub wiki page(github.com/ZFYL/zipper/wiki/Functions).
来源:https://stackoverflow.com/questions/24084631/find-files-modified-between-two-dates-using-php