user482024
user482024

Reputation: 95

converting timestamp to date gives wrong date in php

I'm having trouble getting the correct date from my timestamp while echoing out from files being pulled from an folder on an ftp.

$it = new DirectoryIterator("blahblahblah/news");
$files = array();
foreach($it as $file) {
if (!$it->isDot()) {
    $files[] = array($file->getMTime(), $file->getFilename());
}}

rsort($files);
 foreach ($files as $f) {
     $mil = $f[0];
     $seconds = $mil / 1000;
     $seconds = round($seconds);
     $theDate = date("d/m/Y", $seconds);
echo "<img src=\"images/content/social-icons/article.png\" width=\"18\" height=\"19\" alt=\"article\">" . $theDate . "-  <a  style=\"background-color:transparent;\" href=\"news/$f[1]\">" . $f[1] . "</a>";
echo "<br>";

 }

I'm sorting the files by timestamp, then trying to echo them out with the filename and a link to the file. The problem is that the date() comes out to january 16 1970... I've put the timestamps into an online converter and they are accurate, so I am confused. I've also rounded the timestamps but that does not help either.

Upvotes: 0

Views: 854

Answers (1)

Tomas Reimers
Tomas Reimers

Reputation: 3292

getMTime returns a Unix Timestamp.

Unix Timestamps are typically the number of seconds since the Unix Epoch (NOT the number of milliseconds). See here.

So this: $seconds = $mil / 1000; is your source of error.

Simply set $seconds = $f[0] and you should be good to go.

Corrected code:

$it = new DirectoryIterator("blahblahblah/news");
$files = array();
foreach($it as $file) {
if (!$it->isDot()) {
    $files[] = array($file->getMTime(), $file->getFilename());
}}

rsort($files);
 foreach ($files as $f) {
     $seconds = $f[0];
     $seconds = round($seconds);
     $theDate = date("d/m/Y", $seconds);
echo "<img src=\"images/content/social-icons/article.png\" width=\"18\" height=\"19\" alt=\"article\">" . $theDate . "-  <a  style=\"background-color:transparent;\" href=\"news/$f[1]\">" . $f[1] . "</a>";
echo "<br>";

 }

Upvotes: 4

Related Questions