简体   繁体   中英

find the days from file's created date

I am trying to get the create date and finding the date diff but was not able to do it. I was able to use new DateTime to use date1.diff as I am getting the date from file with filemtime .

Can someone point me to right direction? Thanks.

<?php
$_filename = realpath('test.txt');
if (file_exists($_filename)) {
    $crdatefile = date("Y-m-d H:i:s",filemtime($_filename));
    $date1 = date("Y-m-d H:i:s");
    $datediff = $crdatefile - $date1;
    echo '$datediff' . $datediff . '____';
    if ($datediff < 0) {$datediff = $datediff * -1;}
echo '$datediff' . $datediff . '____';

    $days = round($datediff / (60 * 60 * 24));

echo 'days' . $days . '____';
    if ($days) {
        echo 'days ' . $days . '____';
        if ($days > 1) {
        //unlink($_filename);
            echo 'file delete' . '____';
        }
    }
    echo 'file after delete' . '____';
}
?>

You can do this pretty easliy, but I'd use filectime instead, since on Windows this would give you the actual creation date, whereas on a Linux systeme, it gives you the date of the last change, which is the best you can get, since no creation dates exist on Linux.

// create a new DateTime object with the timestamp returned by the file function
// pass it as format "U" (unix timestamp)
$fileTime = DateTime::createFromFormat('U', filectime($_filename));

// now just diff from a fresh DateTime object (date = now)
$daysSinceFileTime = $filetime->diff(new Datetime())->days;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM