【问题标题】:php filemtime 24 hr formatphp filemtime 24 小时格式
【发布时间】:2012-06-04 13:16:27
【问题描述】:

我创建了这段代码来获取文件最后一次被触摸的日期,然后以 AM/PM 格式显示给用户。

它似乎没有工作。我知道我很接近;我做错了什么?

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

输出:最后更新时间:1969 年 12 月 31 日 06:59 PM

【问题讨论】:

    标签: php date format


    【解决方案1】:

    试试这个:

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

    在您的代码中,这一行:

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

    由于 filemtime 返回一个 UNIX 时间戳,然后您将其作为第一个参数传递给 date(),因此无法工作。即使这确实有效,您也会将该日期转换回带有strtotime() 的 UNIX 时间戳,然后再次转换回日期字符串,这似乎有点低效。

    还要考虑如果文件不存在会发生什么,$date 是否已在代码的其他位置设置?

    【讨论】:

    • 该文件将永远存在,所以我不关心。我现在正在尝试您的修复。请稍等。
    • 在这种情况下,也许将 echo 移到 if 语句中?
    • 代码就像一个魅力。感谢您的简单修复:) 我会尽快接受(在接下来的 4 分钟内被阻止)
    【解决方案2】:
    $date = date(filemtime($filename));
    

    那条线是错误的。 date() 的第一个参数是格式字符串。替换为:

    $date = filemtime($filename);
    

    另外,您不需要对时间戳执行strtotime(),只需按原样使用:

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

    【讨论】:

      猜你喜欢
      • 2012-06-15
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多