webmaster alex l
webmaster alex l

Reputation: 663

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

Upvotes: 4

Views: 9140

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173662

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

That line is wrong. First argument to date() is a format string. Replace with:

$date = filemtime($filename);

Also, you don't need to perform strtotime() on a timestamp, just use as is:

echo date('F d Y h:i A', $date);

Upvotes: 0

Tim Fountain
Tim Fountain

Reputation: 33148

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?

Upvotes: 7

Related Questions