How to compare the time in php? You need to know that the time entered in the form is not less than 8:00 and not more than 20:00.

  • one
    if (strlen($s) < 5) $s = "0"+$s; return $s>="08:00" && $s<= "20:00"; Well, or something like that ... - pavel
  • What is the "s", "s.length"? and "08:00" in this case is just a string of text. Is it generally in what language? - Jonny Manowar
  • pseudo language it was. - pavel
  • Why do I need your pseudo language? Some kind of nonsense. I can't compare strings. I need time to compare, and if to do through the Date object, then I also need to add the date - Jonny Manowar
  • one
    I'm afraid here even a ready answer might not work. - Aquinary

4 answers 4

 $start_time = new DateTime($date . $start); $end_time = new DateTime($date . $end); $start_time_start_limit = new DateTime($date . "08:00"); $start_time_end_limit = new DateTime($date . "20:00"); $error = ''; if ($start_time > $end_time) $error .= "End of time can not bіt less than the start time<br />"; if ($start_time < $start_time_start_limit) $error .= "Start time can not bit less 8:00<br />"; if ($start_time > $start_time_end_limit) $error .= "Start time can not bit more 20:00<br />"; 
     function timeIn($time, $min, $max) { $time = strtotime($time); return strtotime($min) <= $time && $time <= strtotime($max); } if (timeIn($_POST['time'], '8:00', '20:00')) { ... } 

      As an option :

        /** * Получить разницу в днях между 2 дат * @param type $date1 * @param type $date2 */ protected function dateDiff($date1, $date2) { $datetime1 = date_create($date1); $datetime2 = date_create($date2); $interval = date_diff($datetime1, $datetime2); return $interval->format('%a'); } 

      By analogy, compare the clock

         <?php function DateCheck($date) { $date_min = new DateTime("8:00"); // минимальное значение времени $date_max = new DateTime("20:00"); // максимальное значение времени $date_now = new DateTime($date); // текущее значение времени // Проверяем, находится ли $date_now в диапазоне if ($date_now >= $date_min && $date_now <= $date_max) { return true; } return false; } if (DateCheck("8:00")) { print("Все хорошо."); } else { print("Все плохо."); }; ?> 

        http://ideone.com/VOOBRr

        • Please try to write more detailed answers. I am sure the author of the question would be grateful for your expert commentary on the code above. - Nicolas Chabanovsky