-1

I have given time picker to select time range the user can select start time and end time respectively.

start time : 11:00 AM end time : 05:00 PM

which is in 12 hours format, now I want to validate time such as start time should be more than 12:00 AM and end time should be less than 12:00 PM (11:59 PM)

Now I'm getting getting time like this:

if(strtotime($start_time) > strtotime('12:00 AM') &&  strtotime($end_time) < strtotime('11:59 PM'))
{
  echo "Time Validated";
}
else
{
  echo "Time not validated";
}
    
glinda93
  • 7,659
  • 5
  • 40
  • 78
user3653474
  • 3,393
  • 6
  • 49
  • 135
  • 2
    Does this answer your question? [PHP: How to compare a time string with date('H:i')?](https://stackoverflow.com/questions/10497929/php-how-to-compare-a-time-string-with-datehi) – glinda93 Jul 18 '20 at 10:15
  • @bravemaster: It did not solve my issue because it is comparing with current time – user3653474 Jul 18 '20 at 10:17
  • I'm not clear what your question is. You show some current code, but don't mention any problems with it; what is it doing or not doing that you need help with? – IMSoP Jul 18 '20 at 10:25

2 Answers2

3

You can create DateTime class from given format and compare them to validate time.

Working code is here :

function isValidTime($input, $start_time = "`12:00 AM", $end_time = "11:59 PM", $format = "h:i A") {
    $input_date = \DateTime::createFromFormat($format, $input);
    $start_date = \DateTime::createFromFormat($format, $start_time);
    $end_date = \DateTIme::createFromFormat($format, $end_time);
    return $start_date <= $input_date && $input_date <= $end_date;
}
glinda93
  • 7,659
  • 5
  • 40
  • 78
  • It would be much nice if you explained how this code works. Code is nice, but it is much better when you actually teach us something and explain why this solution works – Dharman Jul 18 '20 at 12:35
0

You have to convert time to DateTime format using DateTime::createFromFormat('H:i a', $time), Try like this:

$start_time="11:00 AM";
$end_time="05:00 PM";
$formatted_start_time = DateTime::createFromFormat('H:i a', $start_time);
$formatted_end_time = DateTime::createFromFormat('H:i a', $end_time);
$time1=DateTime::createFromFormat('H:i a', "12:00 AM");
$time2 =DateTime::createFromFormat('H:i a', "11:59 PM");

if($formatted_start_time > $time1
   &&  $formatted_end_time < $time2 )
{
  echo "Time Validated";
}
else
{
  echo "Time not validated";
}
Ranjeet
  • 539
  • 5
  • 12