I have simple DateTime lesson. I'm comparing the 2 DateTime objects and they dont work right. I've tried swapping things around and it still fails. It fails when I enter the current date manually, even if the date is the same. I have to enter a date manually though. Thanks for any help. Heres the function:
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
}
}
I changed everything to make format comparisons, but now the lowest date echos even when I put in a future date. Heres what happens:
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);
}
}
I've been playing with this, and I got it to work by using some of both. I think this is not the way its supposed to work and might cause problems with some other date now that im unaware of. Heres what I did:
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';
}
}
</div>