我得到这样的日期/时间格式来比较:
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