用提交按钮减去两个日期

时间:2018-09-30 13:14:39

标签: javascript date event-listener subtraction

我有两个日期相减的问题。这一切都从两个输入开始。一种是日期,一种是提交按钮。在#ekran段上,需要显示datePicked是否低于今天的日期。它表明我们需要在将来选择某个日期。否则,它将计算今天的日期和我们选择的某个日期之间的差。

当我这样做时,它说的是NaN。我知道我在某个地方搞砸了,但我不知道它在哪里。可能在var d = newDate(),需要正确格式化日期。还是我错了?帮帮我。

p.s。它需要通过DOM lvl 2的方式与eventListener一起完成。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="date">
    <input type="submit" value="submit">

    <p id="ekran"></p>


    <script>
     var button = document.querySelector("[type=submit]").addEventListener('click', racunaj);

     function racunaj() {
        var d = new Date();
        d.setDate(30,9,2018);
        var datePicked = document.querySelector("[type=date]").value;

        var diff = document.getElementById("ekran").innerHTML = datePicked;




        if (datePicked< d) {
            "The Picked date need to be bigger then todays date";
        } else {
            return diff;
        }
     }
     </script>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

如果您想比较某物是多于还是少,则必须首先使它们具有相同的类型。

一个JavaScript Date对象具有一个称为“ getTime()”的内置函数,该函数可用于将日期转换为数字。 一旦有了两个数字,就可以轻松比较这两个数字。

我重写了您的脚本来演示这一点。

    var button = document.querySelector("[type=submit]").addEventListener('click', racunaj);

     function racunaj() {
//       first I make the two variables into a number that can be compared

       var currentTimeAndDate = new Date().getTime();
        var datePicked = new Date(document.getElementById("myDate").value).getTime();

// as you see on the console, they are now two numbers that can be compared.      

       console.log(datePicked, currentTimeAndDate)

//then you just do your logic and output different stuff. 

       if(datePicked < currentTimeAndDate){
       var diff = document.getElementById("ekran").innerHTML = "you chose past" 
      }
       else if(datePicked > currentTimeAndDate){
       var diff = document.getElementById("ekran").innerHTML = "you chose future"          
       }
       else{
        var diff = document.getElementById("ekran").innerHTML = "you did not choose" 
       }
     }

这是一个codepen: https://codepen.io/anon/pen/qJEGme?editors=1011

答案 1 :(得分:1)

您可以像这样更改代码(这是我的上一个答案,我将其总结为增加与您代码的相似性):

 window.onload=function(){
    document.querySelector("[type='submit']").addEventListener('click', racunaj); 
   function racunaj() {
        var d = new Date();
        d.setDate(30,9,2018);
        var datePicked = new Date(document.querySelector("[type=date]").value); 
        var diff = datePicked.getTime()-d.getTime();
        document.getElementById("ekran").innerHTML=diff<0 ? "The Picked date need to be bigger then todays date" : diff +" (days: "+(diff/1000/60/60/24).toFixed(2)+")";
        return diff;
     }
}

您可以检查结果online!