使用输入类型“日期”查找两个日期之间的差异

时间:2017-09-25 08:38:06

标签: javascript jquery html date difference

我很好奇为什么我的代码无法正常运行。我从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);

}

2 个答案:

答案 0 :(得分:0)

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

应替换为

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

如果 span 是HTML元素的ID。

答案 1 :(得分:0)

我找到了你的问题 它不是来自跨度,问题来自javascript 你应该将字符串日期解析为js new Date 你也有一个在几秒钟内输入拼写错误的应该是毫秒的内容

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

检查此代码: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