我有简单的DateTime课程。我正在比较2个DateTime对象,他们没有正确工作。我试过交换东西,但仍然失败。当我手动输入当前日期时,即使日期相同,也会失败。我必须手动输入日期。谢谢你的帮助。继承人的功能:php DateTime对象比较
function dtcompare(){
//I make the date the same as the current
//date and it doesnt echo that its equal.
$date1 = new DateTime('5/9/2015'); //a date entered
$date2 = new DateTime(); //the current date
$mdy = 'n/j/Y'; //the format
if($date1 == $date2){
echo "d1 == d2"; //This should be echoing
}
elseif($date1 > $date2){
echo "d1 > d2";
}
elseif($date1 < $date2){
echo " d1 < d2 "; //but this always echos
}
}
我改变了一切,使格式比较,但现在最低的日期回声,当我把即使是在将来的日期。继承人发生了什么:
function dtcompare(){
$date1 = new DateTime('5/18/2015'); //a future date
$date2 = new DateTime(); //the current date
$mdy = 'n/j/Y'; //the format
if($date1->format($mdy) == $date2->format($mdy)){
echo "d1 == d2";
}
elseif($date1->format($mdy) > $date2->format($mdy)){
//This will echo if the date is in the next month 6/1/2015
echo "d1 > d2";
}
elseif($date1->format($mdy) < $date2->format($mdy)){
//This echos even though it's not 5/18/2015 yet!
echo $date1->format($mdy)."d1 < d2".$date2->format($mdy);
}
}
我一直在玩这个,我得到它通过使用一些双方的合作。我认为这不是它应该工作的方式,并且可能会导致现在还没有意识到的其他日期的问题。继承人我所做的:
function dtcompare(){
$date1 = new DateTime('5/12/2015'); //a future date
$date2 = new DateTime(); //the current date
$mdy = 'n/j/Y'; //the format
//Using the datetime->format for == comparisons and the other
//way for datetimes greater or less than. This works, but I think this is NOT
//how this should work though. It feels like a rig for something that
//should work one way (DateTime->format() comparison) or another (DateTime comparison w.o format)
if($date1->format($mdy) == $date2->format($mdy)){
echo 'date1 and date2 have the same date and time';
}
elseif($date1 > $date2){
echo 'date1 > date2 meaning its a later date and time';
}
elseif($date1 < $date2){
echo 'date1 < date2 meaning its an earlier date and time';
}
}
感谢您的回复。我更新了你的建议,但DateTime对象表示较大的日期(5/18/2015)低于今天的日期(5/9/2015)。如果我使用$ date-> format()比较w.o,那么这个相同的比较工作。它不应该以任何方式工作? – Zapp
@Zapp是的只是格式化,因为你想要的日期,然后你可以比较它们 – Rizier123
@Zapp现在更新我的答案。在您的格式顺序有所不同之前,因为它比较了字符串,所以现在只需要时间戳,它应该都可以正常工作 – Rizier123