javascript 使用时间选择器选择的 jQuery 验证开始时间和结束时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14052432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery-validating start time and end time selected using time picker
提问by Midhun
I want to validate start time and end time selected using timepickerwhich is in 12 hr format. The end time should be greater than the start time. I used an if
statement but when the test is using values such as 8:00 AM as start time and 1:00 PM as end time, it is not working. What can I do to solve this problem. Someone please help me with this. I am stuck with this since yesterday. I want just time,i don't need date.
我想验证使用12 小时格式的timepicker选择的开始时间和结束时间。结束时间应大于开始时间。我使用了一个if
语句,但是当测试使用诸如 8:00 AM 作为开始时间和 1:00 PM 作为结束时间之类的值时,它不起作用。我能做些什么来解决这个问题。有人请帮我解决这个问题。从昨天开始我就坚持这个。我只想要时间,我不需要日期。
$("#dateTimeAddButton").click(function ()
{
var Date=$('#myDatePickerId').val()
var startTime = $('#i').val();
var endTime = $('#i1').val();
if (startTime > endTime)
{
alert('End time always greater then start time.');
}
});
回答by Shiplu Mokaddim
First convert to lowest denominational (minute here). Then compare it.
首先转换为最低面额(此处为分钟)。然后比较一下。
st = minFromMidnight(startTime);
et = minFromMidnight(endTime);
if(st>et){
alert("End time must be greater than start time");
}
function minFromMidnight(tm){
var ampm= tm.substr(-2)
var clk = tm.substr(0, 5);
var m = parseInt(clk.match(/\d+$/)[0], 10);
var h = parseInt(clk.match(/^\d+/)[0], 10);
h += (ampm.match(/pm/i))? 12: 0;
return h*60+m;
}
回答by Mukesh Salaria
please try that below code in case you have length of time more than 6 char like 10:00am instead of 9:00am will throw error above code.
请尝试下面的代码,以防您的时间长度超过 6 个字符,例如 10:00 am 而不是 9:00 am 会在代码上方抛出错误。
I did minor changes in above code and it worked like charm for me.
我对上面的代码做了一些小改动,它对我来说很有魅力。
$('#btnSubmit').on('click', function () {
var startTime = $('#txtJobStartTime').val();
var endTime = $('#txtJobEndTime').val();
var st = minFromMidnight(startTime);
var et = minFromMidnight(endTime);
if (st > et) {
alert('End time always greater then start time.');
return false;
}
function minFromMidnight(tm) {
var ampm = tm.substr(-2);
var clk;
if (tm.length <= 6) {
clk = tm.substr(0, 4);
} else {
clk = tm.substr(0, 5);
}
var m = parseInt(clk.match(/\d+$/)[0], 10);
var h = parseInt(clk.match(/^\d+/)[0], 10);
h += (ampm.match(/pm/i)) ? 12 : 0;
return h * 60 + m;
}
});