如果输入日期大于js中定义的日期,如何发出警报

how to alert if the input date is greater than defined date in js

本文关键字:日期 何发出 定义 输入 大于 js 如果      更新时间:2023-09-26

我的表单中有一个输入日期字段如果输入日期大于我之前定义的任何日期,我需要提醒错误这是我的代码:

$(document).ready(function () {
    var date = new Date(2016,2,1); //the defined date is 1 March 2016
    var day = date.getDate();
    var month = date.getMonth();
    month = month + 1;
    if(day < 10){
        day = '0' + day;
    }
    if(month < 10){
        month='0'+month;
    }
    someday = day + '/' + month + '/' + date.getFullYear();
    $("#q1 input").blur(function(){   //#q1 is the ID for the input field.
        if($('#q1 input').val() > someday){
            alert('the input is bigger than the defined');
        }else{  
            alert('the defined is bigger than the input ');
        }
    });
});

比较日期是非常直接的。大多数运算符强制操作数为数字,Dates返回其时间值,以便查看今天是在2016年3月1日之前还是之后,创建两个Date并进行比较:

var epoch = new Date(2016,2,1); // Create date for 2016-03-01T00:00:00
var now   = new Date();         // Create a date for the current instant
now.setHours(0,0,0,0);          // Set time to 00:00:00.000
if (now < epoch) {
  alert('Before 1 March, 2016');
} else {
  alert('On or after 1 March, 2016');
}

或者更紧凑一点:

alert((now < epoch? 'Before':'On or after') + ' 1 March, 2016');

您可能希望按照日期形式比较值,而不是按照您的方式进行比较。将输入值转换为日期形式,并将其与变量"date"进行比较。

将输入日期与您定义的所需日期进行比较。例如:

var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();

如果你觉得这很棘手,那么有一个很棒的js库moment.js。它在玩日期游戏时非常有用。

$(document).ready(function () {
    var date=new Date(2016,2,1); //the defined date is 1 March 2016
    var fixedDate = returnDate(date);// convert date in dd/mm/yyyy format
 
    //#q1 input will search a child input inside an #q1 dom element, which probably not the case
    // input#q1 will refer to input with id #q1
   // You can directly query the input since it has id #q1 so #q1 input is not correct

$("#q1").blur(function(){   //#q1 is the ID for the input field.
 var d2 = new Date($('#q1').val());
 var inputDate = returnDate(d2); // convert input date in dd/mm/yyyy format
 if(inputDate > fixedDate){ // compare two dates
  console.log('the input is bigger than the defined');
  }else{    
  console.log('the defined is bigger than the input ');
}
});
});
// Write a general function to convert date in dd/mm/yyyy format
function returnDate(date){
   var day=date.getDate();
    var month=date.getMonth();
    month=month+1;
    if(day<10){
    day='0'+day;
 }
   if(month<10){
   month='0'+month;
 }
 var someday=day+ '/' + month + '/' + date.getFullYear();
  return someday;
}

JSFIDDLE

编辑1

使用三元运算符代替if-else

inputDate > fixedDate? (console.log("the input is bigger than the defined")):(console.log("the defined is bigger than the input"))

使用三元运算符