【问题标题】:converting timestamp to date gives wrong date in php将时间戳转换为日期会在 php 中给出错误的日期
【发布时间】:2012-09-11 02:17:20
【问题描述】:

在从 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>";

 }

我正在按时间戳对文件进行排序,然后尝试使用文件名和文件链接来回显它们。 问题是 date() 出现在 1970 年 1 月 16 日...我已将时间戳放入在线转换器中,它们是准确的,所以我很困惑。 我还对时间戳进行了四舍五入,但这也无济于事。

【问题讨论】:

    标签: php date timestamp


    【解决方案1】:

    getMTime 返回一个 Unix 时间戳。

    Unix 时间戳通常是自 Unix 纪元以来的秒数(不是毫秒数)。 See here.

    因此:$seconds = $mil / 1000; 是您的错误来源。

    只需设置$seconds = $f[0],您就可以开始了。

    更正的代码:

    $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>";
    
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 2021-03-13
      • 2013-12-17
      • 2013-09-12
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      相关资源
      最近更新 更多