Necesito comparar la diferencia horaria entre "fecha y hora de hoy" y dos fechas en el futuro. Estas fechas también incluyen información de tiempo.
En este momento tengo el problema de que la "condición if" no arroja el resultado esperado.
Ese es el código y el ejemplo en vivo:
$date_a = new DateTime('now'); $date_b2 = new DateTime('wednesday + 7 day 08:00'); $date_c2 = new DateTime('saturday + 7 day 20:00'); $intervaln = date_diff($date_a,$date_b2); $interval2n = date_diff($date_a,$date_c2); $diff1n = $intervaln->format('%d d. %h h. %i min.'); $diff2n = $interval2n->format('%d d. %h h. %i min.'); if ($diff1n > $diff2n) { echo $diff1n; } else if ($diff1n < $diff2n) { echo $diff2n; } Como puede ver, genera la segunda condición, pero debería ser la primera, ya que $diff1n tiene una diferencia de tiempo mayor que $diff2n .
¿Cuál es la forma correcta de comparar estas fechas y horas entre sí?
Pruebe strtotime() en los tiempos.
$diff1n = $intervaln->format('%d d. %h h. %i min.'); $diff2n = $interval2n->format('%d d. %h h. %i min.'); $d1=strtotime($diff1n); $d2=strtotime($diff2n); if ($d1> $d2) { echo $diff1n; } else if ($d1< $d2) { echo $diff2n; }Puede convertir las fechas a marca de tiempo usando la función setTimestamp(), luego obtenga la diferencia entre los dos, divídala por el número de segundos que hacen que un día redondee a .2 flotante e imprímalo como "2 días a partir de ahora" y luego compare al no. de días es decir
// $diffdateAandNowtime is the difference between the uni time of dateA and nowtime // $diffdateBandNowtime is the difference between the uni time of dateB and nowtime $diffdateAandNowtime = 4600; $diffdateBandNowtime = 5600; $nowtime = 36000; //time here is in seconds if( $diffdateAandNowtime > $diffdateBandNowtime ) { //run some code here echo $diffdateAandNowtime; } elseif( $diffdateBandNowtime > $diffdateAandNowtime ) { echo $diffdateAandNowtime; }