PHP中的strtotime for dd MM yyyy

时间:2019-05-08 10:21:51

标签: php strtotime

尝试时:

echo "<br />".$opening_time = "02 May 2019 - 03:10";
echo "<br />".$closing_time = "12 May 2019 - 13:40";
echo "<br />".$string_opening_time = strtotime($opening_time);
echo "<br />".$string_closing_time = strtotime($closing_time);
echo "<br />".$diffrence_time = $string_closing_time - $string_opening_time;

结果是:

  

2019年5月2日-03:10 12

     

2019年5月-13:40

     

// 2空行

     

0

为什么将其转换为strtotime时为空白?

1 个答案:

答案 0 :(得分:4)

无法识别格式d M Y - H:i,但是如果您知道使用DateTime::createFromFormat()将采用哪种格式,则可以将其重新创建为DateTime对象。

创建两个DateTime对象,并在它们上使用diff()方法,这将为您带来不同。

$opening_time = "02 May 2019 - 03:10";
$closing_time = "12 May 2019 - 13:40";

$open = DateTime::createFromFormat("d M Y - H:i", $opening_time);
$close = DateTime::createFromFormat("d M Y - H:i", $closing_time );
$diff = $open->diff($close);

echo $opening_time."<br />\n";
echo $closing_time."<br />\n";
echo $diff->d." days ".$diff->h." hours ".$diff->m." minutes ";

如果您需要以秒为单位的差异,请使用getTimestamp()方法。

$open = DateTime::createFromFormat("d M Y - H:i", $opening_time);
$close = DateTime::createFromFormat("d M Y - H:i", $closing_time );
$diff = $close->getTimestamp() - $open->getTimestamp();

echo $opening_time."<br />\n";
echo $closing_time."<br />\n";
echo $diff;