使用JavaScript限制日期范围 [英] Date range restriction with JavaScript
问题描述
有两个类型为text的输入字段,用于以mm / dd / yyy格式写入开始日期和结束日期。我需要一个JavaScript函数来检查这些输入日期之间的日期范围间隔是否超过14天。最长日期应为当前日期。是否有插件或快速解决方案?我尝试使用jQuery UI datepicker可以正常工作,但我有一个自定义的GetElementByClassName函数与jQuery冲突。
There are two input fields of type text to write a start date and end date in format mm/dd/yyy. I need a JavaScript function to check that the date range interval between those entered dates does not exceed 14 days. And the maximum date should be the current date. Is there a plugin or a fast solution for this? I tried to use the jQuery UI datepicker which would work fine, but I have a custom GetElementByClassName function which conflicts with jQuery.
谢谢。
推荐答案
以下片段应该会给你一些想法。
The following snippets should give you some ideas.
<script>
var date1 = '01/14/2011';
var date2 = '01/25/2011';
// calculate the number of days between date1 and date2
var daysBetween = new Date(date2).getTime() - new Date(date1).getTime();
alert('days between = ' + daysBetween / 86400000);
// check date3 against current date
var now = new Date();
var date3 = new Date('04/20/2011');
if (date3 < now)
alert('date3 is less than current date');
</script>
所以要组合成一个函数,你可以这样做:
So to combine into a function, you could do something like this:
<script>
function checkDates(date1, date2) {
// calculate the number of days between date1 and date2
var daysBetween = (new Date(date2).getTime() - new Date(date1).getTime()) / 86400000;
if (daysBetween > 14)
return false;
var now = new Date();
if (date2 < now)
return false;
return true;
}
这篇关于使用JavaScript限制日期范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!