PHP - 格式化日期

Con*_*ure 0 php string compare date seconds

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

hek*_*mgl 5

使用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';
}
Run Code Online (Sandbox Code Playgroud)

注意:当然,您必须以显示年,月和日的差异的方式扩展输出.我在示例中没有这样做,因为我很懒...因为字符串对于示例来说太长了...;)