0

This is my code. Why 2:00:00 AM <= 1:00:00 AM is false?

    $new_in_time = new DateTime(date("H:i:s", strtotime('1:00:00')));
    $new_get_in = new DateTime(date("H:i:s",strtotime('2:00:00')));
    if($new_in_time <= $new_get_in){
    echo "true";
    }else{
    echo "false";
    }
LF00
  • 27,015
  • 29
  • 156
  • 295
SE.Edward
  • 201
  • 3
  • 12
  • 1
    Possible duplicate of [How to compare two dates in php](https://stackoverflow.com/questions/8722806/how-to-compare-two-dates-in-php) – treyBake Oct 25 '19 at 08:53
  • Yes. But this is my condition i have default shift in_time 2:00 AM and out_time 11:00 AM, I just want to know the less than in my in_time and greater than in my out time? – SE.Edward Oct 25 '19 at 09:06
  • Yes i am, My out time is 11:00:00 and i want to know it the greater than of my time out and less than in my in time 2:00:00. But the problem is 1:00:00 is greater than 2:00:00 – SE.Edward Oct 25 '19 at 09:21
  • why not just use `DateTime` alone, no need to combine `date` and `strtotime` – Kevin Oct 25 '19 at 09:33
  • _“Why 2:00:00 AM <= 1:00:00 AM is false?”_ - because you are comparing _strings_ here, and that happens character-by-character, from left to right. `2` comes after `1` in the order of characters in any given character encoding, and therefor `2:00:00 AM` is considered _greater_ than `1:00:00 AM` directly after comparing the first characters of both. – 04FS Oct 25 '19 at 09:41
  • `This is my code. Why 2:00:00 AM <= 1:00:00 AM is false?` 2am is after 1am, where is 11am coming from (in comments)?. This question is obviously unclear and probably a misreading/misunderstanding of something. – AD7six Oct 25 '19 at 10:48

3 Answers3

1

try using this :

SELECT TIMESTAMPDIFF(HOUR,'2019-10-10 2:00:00','2019-10-10 1:00:00') as TIME_RESULT
SE.Edward
  • 201
  • 3
  • 12
Bap mop
  • 320
  • 2
  • 15
0

The output is correct. If you want to change the logic, you can reverse the condition from ($new_in_time <= $new_get_in) to ($new_in_time > $new_get_in)

  • But this is my condition i have default shift in_time 2:00 AM and out_time 11:00 AM, I just want to know the less than in my in_time and greater than in my out time? – SE.Edward Oct 25 '19 at 09:04
0
if (($new_get_in <= $new_in_time && $new_get_out >= $new_out_time)) {
   echo "true";
}
else{
   echo "false";
}

// try this
Gerry
  • 73
  • 6