如何验证输入时间在javascript中两个给定时间之间

时间:2019-06-23 07:00:48

标签: javascript jquery-ui

我必须验证开始时间和结束时间,是否在文本框中输入的值在给定值之间。如果开始时间和结束时间在同一天,则工作正常,但是如果结束日期不同,则验证失败。我在StackOverflow上看到了许多其他链接,但是它不起作用。

How to check if one DateTime is later than another in javascript

How can I compare two time strings in the format HH:MM:SS?

How to check if one DateTime is later than another in javascript enter image description here

<html>
<script language="javascript">
    jQuery(document).on('change',".timepicker",function(){
var selectedTime = new Date("November 13, 2018 " + jQuery(this).val());
var startLimit = new Date("November 13, 2018 " + jQuery(this).data('starttime'));
var endLimit = new Date("November 13, 2018 " + jQuery(this).data('endtime'));
var start_time_val = new Date("November 13, 2018 " + $("input[name=start_time]").val());
var end_time_val = new Date("November 13, 2018 " + $("input[name=end_time]").val());
var elementName = jQuery(this).attr('name');
var valid = moment(jQuery(this).val(), "H:mm a", true).isValid();
var time = new Date("November 13, 2018 " + selectedTime);
jQuery(this).next('span.error').text('');
var error_msg = jQuery(this).data('erro_msg');


if(valid){
    if(elementName == 'start_time'){

        if(selectedTime >= startLimit && endLimit > selectedTime){

            console.log("selected Time less than start limit");
        }else{
            console.log("selected Time is less than start limit");
            jQuery(this).next('span.error').text(error_msg);
        }
    var endTimeSelected = jQuery(this).next('input').val();
    }else if(elementName == 'end_time'){


        if(selectedTime >= startLimit && endLimit > selectedTime){
        }else{
            jQuery(this).next('span.error').text(error_msg);
        }
        var endTimeSelected = jQuery(this).next('input').val();
    }else if(elementName == 'end_time'){
        if(selectedTime <= endLimit && selectedTime <= endLimit){

        }
        else{

            jQuery(this).next('span.error').text(error_msg);
        }

        var startTimeSelected = jQuery(this).prev('input.timepicker').val();
}
}else{
    jQuery(this).next('span.error').text(error_msg);
}

});
        </script>

<input type="text" name="start_time" value="6:15 AM" class="form-control timepicker" autocomplete="off" requried="1" data-starttime="6:00 AM" data-endtime="12:00 PM" data-erro_msg="Please select time between 6:00 AM-12:00 PM">

    <input type="text" name="end_time" value="7:15 AM" class="form-control timepicker" autocomplete="off" requried="1" data-starttime="6:00 AM" data-endtime="12:00 PM" data-erro_msg="Please select time between 6:00 AM-12:00 PM">
       </html>

1 个答案:

答案 0 :(得分:0)

问题在于解析。 Date.parse()不读取am / pm添加。您可以使用moment.js或将上午/下午分开,并在下午增加12小时