【问题标题】:PHP - Formatting a DatePHP - 格式化日期
【发布时间】:2013-06-02 23:29:01
【问题描述】:

我有一个日期存储到一个字符串变量中:Sun Jun 02 08:54:12 EDT 2013。如何将其转换为日期变量以比较当前日期与提供的日期之间的时差。谢谢!

【问题讨论】:

  • 您从哪里获取日期、数据库、文本字符串、csv 文件?你能告诉我们你到目前为止尝试过的代码吗?谢谢
  • 我认为您只是在寻找函数 strtotime() [php.net/manual/fr/function.strtotime.php]
  • 我已经获得了我想要比较的日期并将其存储到一个字符串中。我想知道从这里做什么......

标签: php string date compare seconds


【解决方案1】:

使用DateTime 类将当前日期与时间字符串进行比较。一旦有了DateTime 对象,您就可以使用DateTime::diff() 方法轻松获得差异。它将返回一个DateInterval 对象,可以使用它的format() 方法打印该对象。

$dt = new DateTime('Sun Jun 02 08:54:12');
$now = new DateTime();

if($now > $dt) {
    $difference = $now->diff($dt);
    echo $difference->format('The time is %H hours %I minutes %S seconds in the past');
} else if ($now < $dt) {
    $difference = $dt->diff($now);
    echo $difference->format('The time is %H hours %I minutes %S seconds in the future');
} else {
    echo 'the time is now';
}

注意:当然,您必须扩展输出,使其另外显示年、月和日的差异。我在示例中没有这样做,因为我很懒... aehhmm 因为示例中的字符串会变得太长... ;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-24
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多