Home > OS >  How to get filemtime compared to current time
How to get filemtime compared to current time

Time:06-25

I need to check the last modified time of my file. I have used filemtime() in PHP for that as below..

 <h6 style="text-align: right" > <?php echo "Content last changed: ".date("F d Y H:i:s.", filemtime("file.js"));?> </h6>

This works fine and I could see the modified time.. Now I need to get this time compared to current time..

As an example , if the file modified 30 seconds ago, it should show Content last changed:30 seconds if the file modifies 5 minutes ago, it should show Content last changed:5 minutes, if the file modified 2 hours ago, it should show accordingly.

Since I am using this method in so many places , I would like to have a function rather than inline code.

Can someone help me on this,

Thanks In advance!

CodePudding user response:

This function gets the time difference in seconds and then converts it to the format 0 hours 0 minutes 0 seconds (0 is used for reference).

function func( $file ) {
    $seconds = time() - filemtime( $file );
    $hours = floor($seconds / 3600);
    $minutes = floor(($seconds / 60) % 60);
    $seconds = $seconds % 60;
    if ( $hours != 0 ) {
        return $hours . ' hours';
    }
    if ( $minutes != 0 ) {
        return $minutes . ' minutes';
    }
    if ( $seconds ) {
        return $seconds . ' seconds ';
    }
}
  • Related