验证日期时间输入以进行调度

我有一个调度系统学校项目,我需要创建一个函数来验证用户输入的日期,检查它是否提前 2 天,而不是星期日,以及是否在工作时间之间。


我正在使用 codeigniter 框架。


//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>


四季花海
浏览 127回答 2
2回答

慕运维8079593

为了完成起见,我将考虑<input type="datetime-local" name="dateTimeInput">作为输入。所以这基本上创建了这种格式:d/m/Y h:i A我在我的浏览器 (Chrome) 上尝试过,它确实做到了。更多信息也在这里:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local因此,考虑到这一点,您可以使用createFromFormat来解析输入并使用DateTime类。$input = DateTimeImmutable::createFromFormat('d/m/Y h:i A', $dateTimeInput);$dt = new DateTime; // nowif (&nbsp; &nbsp; ($input >= $input->setTime(8, 0) && $input <= $input->setTime(17, 0)) && // time is between 8 to 5&nbsp; &nbsp; $input->format('l') !== 'Sunday' && // is not sunday&nbsp; &nbsp; $dt->diff($input)->d >= 2 // is greater or more than two days) {&nbsp; &nbsp; return true;}return false;这是一个示例输出旁注:我还应该指出type="datetime-local" Firefox 浏览器不支持,应该考虑使用实时日期时间插件代替。如果用户碰巧使用 Firefox,您应该准备回退。

达令说

您可以使用以下函数并从控制器调用它。function checkDateConditions( $dateTimeInput ) {&nbsp; &nbsp; //Make DateTime Object using the input&nbsp; &nbsp; $inputDate = new DateTime( $dateTimeInput );&nbsp; &nbsp; //Get the Hour from the Date Input&nbsp; &nbsp; $inputHour = $inputDate->format('G');&nbsp; &nbsp; //Check Time is between 8AM and 5PM ( 5PM is = 17)&nbsp; &nbsp; if( $inputHour < 8 || $inputHour > 17) {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; //This Returns 7 for Sunday&nbsp; &nbsp; $dayOfWeek = $inputDate->format('N');&nbsp; &nbsp; //If its Sunday we return false&nbsp; &nbsp; if( $dayOfWeek == 7) {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; //Calculate Date Difference&nbsp; &nbsp; $now = new DateTime( Date('Y-m-d') );&nbsp; &nbsp; $diff =&nbsp; $inputDate->diff($now);&nbsp; &nbsp; //If date difference is greater than 2 days return false&nbsp; &nbsp; if( $diff->days > 2 ) {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; //If it reaches here it means all conditions are met so retrun true.&nbsp; &nbsp; return true;}
打开App,查看更多内容
随时随地看视频慕课网APP