我有簡單的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