【问题标题】:Comparing unix timestamps in PHP [closed]比较 PHP 中的 unix 时间戳 [关闭]
【发布时间】:2012-11-21 12:38:45
【问题描述】:

在 PHP 中我有:

$diff = abs(strtotime(date('m/d/Y h:i:s')) - strtotime($latest));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
echo floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

我如何获得以秒为单位的差异?我尝试了以下方法:

$diff = abs(strtotime(date('m/d/Y h:i:s')) - strtotime($latest));

【问题讨论】:

标签: php html mysql


【解决方案1】:

改用DateTime,它会让你的代码更干净。

$latest = new DateTime($latest);
$now = new DateTime();

$diff = $latest->diff($now);
echo $diff->format('%y years %m months %d days');

【讨论】:

  • 我遇到了DateTime 的问题。你能看看这个program
【解决方案2】:

时间戳只是从 1970 年 1 月 1 日开始的几秒。所以它很简单:

<?php
    $now = time();
    $latest = "21-11-2012 14:44";
    $latest = strtotime($latest);
    $diff = ($now - $latest);
    //$diff = Number of seconds difference between now and 21-11-2012 14:44
?>

还可以查看DateTime 类,它在处理日期时具有更多功能。

【讨论】:

  • 由于某种原因,当我在 MySQL 中插入带有 CURRENT_TIMESTAMP 的字段然后将其拉出并使用您的方法将其比较为 &latest 时,我得到 21586 秒
猜你喜欢
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多