Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate datetime input for scheduling

I have a scheduling system school project, I need to create a function that validates the date entered by the user, check if it is 2 days ahead, not Sunday and it is between working hours.

Im using codeigniter framework.

//my controller looks like this:
public function checkDateTimeInput(){
        $dateTimeInput = $this->input->post('dateTimeInput');
        if($dateTimeInput /*Greater than 2 days or more*/ && /*not sunday*/ && /*between 8AM-5PM*/){
            return true;
        }else{
            return false;
        }
    }



//in my view:
<?php echo form_open('schedules/checkDateTimeInput'); ?>
    <input type="datetime-local" name="dateTimeInput">
    <input type="submit" value="submit">
</form>
like image 465
pj_seno Avatar asked Apr 09 '26 15:04

pj_seno


1 Answers

For completion's sake, I'm going to consider <input type="datetime-local" name="dateTimeInput"> as the input.

So this basically creates this format:

d/m/Y h:i A

I tried it on my browser (Chrome) and it does that. More info here also:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local

So taking that into consideration, you can use createFromFormat to parse the input and use DateTime class.

$input = DateTimeImmutable::createFromFormat('d/m/Y h:i A', $dateTimeInput);
$dt = new DateTime; // now
if (
    ($input >= $input->setTime(8, 0) && $input <= $input->setTime(17, 0)) && // time is between 8 to 5
    $input->format('l') !== 'Sunday' && // is not sunday
    $dt->diff($input)->d >= 2 // is greater or more than two days

) {
    return true;
}

return false;

Here's a sample output

Sidenote: I should also point out that type="datetime-local" is not supported in Firefox browser and should consider using a real date time plugin instead. If the user happens to use Firefox, you should prepare a fall back.

like image 65
Kevin Avatar answered Apr 12 '26 07:04

Kevin