0

I'm trying to compare between two times: the $now_time and $finish_time.
the $finish_time is +100 minute after $starting_time.
i want to add if else on this times to do: if $now_time is more than $finitsh_time the result echo true, else echo false

<?php
    date_default_timezone_set("Asia/Tehran");
    $now_time = date("Y-m-d h:i:s");

    $starting_time = "2020-02-08 20:30:00";
    $finish_time = strtotime("+100 minutes", strtotime($starting_time));

    $date1 = DateTime::createFromFormat('Y-m-d h:i:s', $now_time);
    $date2 = DateTime::createFromFormat('Y-m-d h:i:s', $finish_time);

    if($date1 < $date2){
        echo "True";
    } else {
        echo "False";
    }
?>
Ali
  • 91
  • 2
  • 9
  • Does this answer your question? [How do I compare two DateTime objects in PHP 5.2.8?](https://stackoverflow.com/questions/961074/how-do-i-compare-two-datetime-objects-in-php-5-2-8) – vicpermir Feb 24 '20 at 11:17
  • yeah, just with a little confusing – Ali Feb 24 '20 at 11:37

2 Answers2

0

Using the DateTime class you could simplify the above code a little:

date_default_timezone_set('Asia/Tehran');
$starting_time = '2020-02-08 20:30:00';


$start=new DateTime( $starting_time );
$end=new DateTime( date( 'Y-m-d H:i:s', strtotime( sprintf( '%s+100minutes', $start->format('y-m-d H:i:s') ) ) ) );

if( $start < $end )echo 'True';
else echo 'False';
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • Thanks RamRaider. Ive added the `now` to your solution and its work how i wants – Ali Feb 24 '20 at 10:46
0

I prefer to use the binary format and only to use human printable dates only for input from and output to user interface. That make programming easier and the code is more efficient -- calculations with broken down dates are time intensive.

So my solution:

# not needed here
# date_default_timezone_set("Asia/Tehran");
# $now_time = time();

# This is the only text-to-bin conversion
$starting_time = strtotime("2020-02-08 20:30:00");
$finish_time = $starting_time + 100*60; // + 100 minutes

# differences and comparing binary times is very easy and efficient
if ( $starting_time < $finish_time ) {
    echo "True";
} else {
    echo "False";
}
Wiimm
  • 2,971
  • 1
  • 15
  • 25