两种不同的日期/时间格式如何确定哪一种更晚?

时间:2013-07-11 10:23:30

标签: php date

我得到这样的日期/时间格式进行比较:

08:18:00 07/11/2013

7/11/2013 9:11:00 AM

如何将每一个转换为格式,以便我可以像这样编写PHP以找出哪一个是以后的日期/时间?

// $time1 will always be in HH:MM:SS MM/DD/YYYY format.
$time1 = "08:18:00 07/11/2013";

// $time2 will always be in MM/DD/YYYY HH:MM:SS format.
$time2 = "7/11/2013 9:11:00 AM";

$time_one = $mytimeconvertdate_time_first($time1);
$time_two = $mytimeconvertdate_date_first($time2);

if ($time_two > $time_one) {
   echo "time_two is later" . "\n";
}  else {
   echo "time_one is later" . "\n";
}

我试过这个,但第二个值不包含日期信息:

<?php
date_default_timezone_set('America/New_York');

// $time1 will always be in HH:MM:SS MM/DD/YYYY format.
$time1 = "08:18:00 07/11/2013";

// $time2 will always be in MM/DD/YYYY HH:MM:SS format.
$time2 = "7/11/2013 9:11:00 AM";

$dt1 = DateTime::createFromFormat("H:i:s m/d/Y", $time1);
$dt2 = DateTime::createFromFormat("m/d/Y H:i:s", $time2);
var_dump($dt1);
var_dump($dt2);
if ($dt1 < $dt2) echo "The first is earlier";

?>

输出结果为:

object(DateTime)#1 (3) {
  ["date"]=>
  string(19) "2013-07-11 08:18:00"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "America/New_York"
}
bool(false)

更正:

<?php
date_default_timezone_set('America/New_York');

//注意:“一个是24小时格式,而另一个是上午/下午12小时。”

// $time1 will always be in HH:MM:SS MM/DD/YYYY format.
$time1 = "08:18:00 07/11/2013";

// $time2 will always be in MM/DD/YYYY HH:MM:SS format. 
$time2 = "7/11/2013 9:11:00 AM";

$dt1 = DateTime::createFromFormat("H:i:s m/d/Y", $time1);
$dt2 = DateTime::createFromFormat("m/d/Y g:i:s a", $time2);
var_dump($dt1);
var_dump($dt2);
if ($dt1 < $dt2) echo "The first is earlier" . "\n";

?>


object(DateTime)#1 (3) {
  ["date"]=>
  string(19) "2013-07-11 08:18:00"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "America/New_York"
}
object(DateTime)#2 (3) {
  ["date"]=>
  string(19) "2013-07-11 09:11:00"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "America/New_York"
}
The first is earlier

3 个答案:

答案 0 :(得分:3)

使用DateTime::createFromFormat从格式化文本中创建两个DateTime个实例。然后,您可以直接比较实例以找到更早的实例。

$dt1 = DateTime::createFromFormat("H:i:s m/d/Y", $time1);
$dt2 = DateTime::createFromFormat("m/d/Y g:i:s a", $time2);

if ($dt1 < $dt2) echo "The first is earlier";
// etc

答案 1 :(得分:1)

使用Carbon (which is an API for PHP's native DateTime)你可以做到:

<?php
$time_one = Carbon::create(2013, 11, 7, 8, 18, 00); // 08:18:00 07/11/2013
$time_two = Carbon::create(2013, 11, 7, 9, 11, 00); // 7/11/2013 9:11:00 AM

if ($time_two->gt($time_one))
{
   echo "time_two is later\n";
}
else
{
   echo "time_one is later\n";
}


编辑:

当然,您不需要使用碳来达到预期效果。但是看看the source of Carbon on GitHub看看它是如何完成的,你将学习如何通过一些例子来实现你的目标。这只是善意的建议。

答案 2 :(得分:0)

您可以执行以下操作:

$date1 = date("Y-m-d-H-i-s", strtotime("08:18:00 07/11/2013"));
$date2 = date("Y-m-d-H-i-s", strtotime("08:18:00 07/11/2013"));

if($date2 > $date1)
    ...