webmaster alex l webmaster alex l - 23 days ago 4
PHP Question

php filemtime 24 hr format

I created this code to get the date a file was last touched then display it to the user in AM/PM format.

It doesn't seem to be working though. I know I'm close; what am I doing wrong?

$filename = 'test.html';
if (file_exists($filename)) {
$date = date(filemtime($filename));
clearstatcache();
}
echo "- last updated: " . date('F d Y h:i A', strtotime($date));


Output: last updated: December 31 1969 06:59 PM

Answer

Try this:

if (file_exists($filename)) {
    $date = filemtime($filename);
    clearstatcache();
}
echo "- last updated: " . date('F d Y h:i A', $date);

In your code, this line:

$date = date(filemtime($filename));

wouldn't work since filemtime returns a UNIX timestamp, which you are then passing as the first parameter to date(). Even if that did work, you are then converting that date back to a UNIX timestamp with strtotime(), and then back into a date string again which seems a little inefficient.

Also consider what happens if the file doesn't exist, will $date have been set elsewhere in your code?

Comments