【问题标题】:Using input type "Date" to find the difference between two dates使用输入类型“日期”来查找两个日期之间的差异
【发布时间】:2017-09-25 08:38:05
【问题描述】:

我很好奇为什么我的代码不能正常运行。我从 html 文件中检索 Date 输入的值,并创建了一个函数来查找差异;但是,span 元素不会更新。请向我解释为什么我错了以及我能做些什么来解决它。谢谢!

Code

const setup = () => {

  let firstDate = $('#firstDate').val();
  let secondDate = $('#secondDate').val();

  const findTheDifferenceBetweenTwoDates = (firstDate, secondDate) => {
    let timeDifference = Math.abs(secondDate.getTime() - 
    firstDate.getTime());

    let millisecondsInADay = (1000 * 3600 * 24);
    let differenceOfDays = Math.ceil(timeDifference / secondsInADay); 

    return differenceOfDays;
  }

 let result = findTheDifferenceBetweenTwoDates(firstDate, secondDate);

 $("span").text(result);

}

【问题讨论】:

    标签: javascript jquery html date difference


    【解决方案1】:
     $("span").text(result); 
    

    应该替换为

    $("#span").text(result);
    

    如果 span 是 HTML 元素的 id。

    【讨论】:

      【解决方案2】:

      我发现了你的问题 它不是来自跨度,问题来自javascript 您应该将字符串日期解析为 js new Date 还有你在 secondsInADay 中有一个错字应该是 millisecondsInADay

      还有一个错误,当文档准备好时代码将运行 这是错误的,因为您正在等待用户的输入 所以我添加了一个提交按钮

      检查此密码:https://codepen.io/hassanalisalem/pen/gGLyvJ

      你的 HTML

      <div class="container">
        <h1>Date Difference!</h1>
        <h1>First Date</h1>
          <input id="firstDate" type ="date">
        <br/>
         <h1>Second Date</h1>
          <input id="secondDate" type ="date">
        <br>
        <h1>Amount of Days: <span id="result"></span></h1>
        <button id="submit">submit</button>
      </div>
      

      你的 js:

      const animateBg = (i) => {
          document.body.style.backgroundColor = 'hsl(' + i + ', 100%, 50%)';
      
          setTimeout(function() {
              animateBg(++i)
          }, i);
      }
      animateBg(0);
      
      const setup = () => {
        let firstDate = $('#firstDate').val();
        let secondDate = $('#secondDate').val();
        const findTheDifferenceBetweenTwoDates = (firstDate, secondDate) => {
        firstDate = new Date(firstDate);
          secondDate = new Date(secondDate);
      
          let timeDifference = Math.abs(secondDate.getTime() - firstDate.getTime());
      
          let millisecondsInADay = (1000 * 3600 * 24);
      
          let differenceOfDays = Math.ceil(timeDifference / millisecondsInADay);
      
          return differenceOfDays;
      
        }
      
        let result = findTheDifferenceBetweenTwoDates(firstDate, secondDate);
        alert(result);
        $("#result").text(result);
      
      
      }
      
      $(document).ready(function () {
        $('#submit').click(function () {
          setup();
        })
      });
      

      现在应该可以了 它在 codepen 上工作

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 2011-10-29
      • 2014-08-15
      • 1970-01-01
      相关资源
      最近更新 更多