简体   繁体   English

如何比较两个全年的日期

[英]How to compare two full year dates

The idea in my example is to allow user to select only the year in to input already selected in from input (have the same year in from and to date input). 在我的例子我们的想法是让用户仅在今年选择to已选定的输入from输入(具有相同的一年,从和日期输入)。

The issue here is that it works fine when we use the date picker but, when we hit manually the date into 'to' input, it compare juste the first number of the year ***8/04/14 , I want to wait until the user finish the full date example 2018/04/14 then I alert OK. 这里的问题是,当我们使用日期选择器时,它工作正常,但是,当我们手动将日期打入“至”输入中时,它会比较年份的第一个数字***8/04/14 ,我要等待直到用户完成完整的日期示例2018/04/14然后我提醒“确定”。 I the actual code, if I take the example : from = 2018/04/14 , to = 2018/05/29 , So it compare 2018/04/14 with from = 8/05/29 , it alert ok in the 8 of 2018 and not in the complete year. 我是实际的代码,如果我举个例子: from = 2018/04/14to = 2018/05/29 ,因此将2018/04/14from = 8/05/29进行比较,它会在8中 from = 8/05/29警报的2018而不是完整的一年。

 $("#from").on("change", function() { year(); var from = $("#from").val(); if (from) { var maxYear = new Date(from).getFullYear(); $("#to").attr("max", maxYear+"-12-31"); $("#to").attr("min", maxYear+"-01-01"); } }); $("#to").on("change", function(){ year(); }); function year() { var from = $("#from").val(); var to = $("#to").val(); if(from && to && new Date(from).getFullYear() != new Date(to).getFullYear()) { $("#to").val(""); alert("OK"); } } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="from">from</div> <input id="from" type="date"> <div class="to">to</div> <input id="to" type="date"> 

Try using 尝试使用

$("#to").on("blur", function(){
   year();
});

That should active the check only after the input loses focus. 只有在输入失去焦点后,才应激活检查。

Change event is triggered when input change, if you want catch user event, or key event you should try to declare all "change code" as stand alone functions and add another eventListener. 输入更改时触发Change事件,如果要捕获用户事件或键事件,则应尝试将所有“更改代码”声明为独立函数并添加另一个eventListener。

Maybe with blur or key down will work as you want but lot of event exist : https://www.w3schools.com/jsref/dom_obj_event.asp 也许可以根据需要使用blurkey down但存在大量事件: https : //www.w3schools.com/jsref/dom_obj_event.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM