如何使用两种不同的日期/时间格式来确定以后的格式? [英] How do two different date/time formats to determine which one is later?
问题描述
我正在获取类似的日期/时间格式:
I'm getting date/time formats like this to compare:
08:18:00 07/11/2013
7/11/2013 9:11:00 AM
操作方法我将它们中的每一个都转换为一种格式,这样我就可以像这样编写PHP以找出哪个是以后的日期/时间?
How do I convert each one of them to a format so I can write PHP like this to find out which one is a later date/time?
// $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";
}
我已经尝试过,但是第二个值不包含日期信息:
I have tried this, but the second value doesn't contain date info:
<?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小时制,带有am / pm。
// Note: "One is 24-hour format while the other is 12-hour with am/pm. "
// $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
推荐答案
使用 DateTime :: createFromFormat
从格式化文本创建两个 DateTime
实例。然后,您可以直接比较实例,以查找时间更早的实例。
Use DateTime::createFromFormat
to create two DateTime
instances from the formatted text. You can then compare the instances directly to find which is earlier in time.
$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
这篇关于如何使用两种不同的日期/时间格式来确定以后的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!