Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
Compare time difference inside if condition

I need to compare the time difference between "todays date and time" and two dates in the future. These dates are including time informations, too.

At the moment I'm having the problem that the "if condition" doesn't output the expected result.

That's the code and the live example:

$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;
    }

As you see it outputs the second condition but it should be the first one since $diff1n has the bigger time difference than $diff2n.

What's the right way to compare these dates and times to each other?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Try strtotime() on the times .

$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;
}
over 4 years ago · Santiago Trujillo Report

0

You can convert the dates to timestamp using the setTimestamp() function, then get the difference between the two, divide it by no of seconds that make a day round of to .2 float and print it like "2 days from now" then compare it to the no. of days i.e

// $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;

        }

refer here for setTimestamp()

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!