var datestr1 = $('#datefield1-id').val();
var datestr2 = $('#datefield2-id').val();
I'd strongly recommend to parse the date strings before comparing them. Javascript's Date object has a parse()-Method, but it only supports US date formats (YYYY/MM/DD). It returns the milliseconds since the beginning of the unix epoch, so you can simply compare your values with > or <.
如果需要不同的格式(例如 ISO 8661) ,则需要使用正则表达式或免费的 date.js 库。
If you want to be super user-fiendly, you can use jquery ui datepickers instead of textfields. There is a datepicker variant that allows to enter date ranges:
引用 jquery.validate.js 和 jquery-1.2.6. js。
将 startDate 类添加到开始日期文本框中。
Add an endDate class to your end date textbox.
将此脚本块添加到页面:-
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("endDate", function(value, element) {
var startDate = $('.startDate').val();
return Date.parse(startDate) <= Date.parse(value) || value == "";
}, "* End date must be after start date");
$('#formId').validate();
});
</script>
var date_ini = new Date($('#id_date_ini').val()).getTime();
var date_end = new Date($('#id_date_end').val()).getTime();
if (isNaN(date_ini)) {
// error date_ini;
}
if (isNaN(date_end)) {
// error date_end;
}
if (date_ini > date_end) {
// do something;
}
我的 addMethod没有 Mike E 的最佳答案那么健壮,但是我正在使用 JqueryUI 数据采集器来强制进行日期选择。如果有人能告诉我如何确保日期是数字,并让方法是可选的,这将是伟大的,但现在这个方法为我工作:
jQuery.validator.addMethod("greaterStart", function (value, element, params) {
return this.optional(element) || new Date(value) >= new Date($(params).val());
},'Must be greater than start date.');
var from = $("#from").val();
var to = $("#to").val();
if(Date.parse(from) > Date.parse(to)){
alert("Invalid Date Range");
}
else{
alert("Valid date Range");
}
$.validator.addMethod("endDate", function(value, element) {
var startDate = $('#date_open').val();
return Date.parse(startDate) <= Date.parse(value) || value == "";
}, "* End date must be after start date");
$('#end_date').on('change', function(){
var startDate = $('#start_date').val();
var endDate = $('#end_date').val();
if (endDate < startDate){
alert('End date should be greater than Start date.');
$('#end_date').val('');
}
});
either you can perform on calendar it will automatically disable previous dates.