Home > Software engineering >  find the days from file's created date
find the days from file's created date

Time:09-23

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' . '____';
}
?>

CodePudding user response:

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;
  • Related