从多个日期输入计算总天数

时间:2021-06-02 02:09:07

标签: javascript html css date

我正在开发一个网站来计算用户在我们家停留的天数。我考虑到他们可能在我们这里住过多次。因此,我想根据他们选择的多个日期计算他们确实与我们在一起的总天数。

但是,我的计算按钮没有给我预期的结果。单周期运行良好。

这是我的代码:

      function calculateEmp() {
      var startDate1 = document.getElementById("startDate1").value;
      var endDate1 = document.getElementById("endDate1").value;
      var startDate2 = document.getElementById("startDate2").value;
      var endDate2 = document.getElementById("endDate2").value;
      var dvtextless60 = document.getElementById("dvtextless60");
      var dvtext61182 = document.getElementById("dvtext61182");
      var dvtextmore183 = document.getElementById("dvtextmore183");
      var Difference_In_Time1 = new Date(endDate1).getTime() - new Date(startDate1).getTime();
      var Difference_In_Days1 = Difference_In_Time / (1000 * 3600 * 24);
      var Difference_In_Time2 = new Date(endDate2).getTime() - new Date(startDate2).getTime();
      var Difference_In_Days2 = Difference_In_Time / (1000 * 3600 * 24);

      if (Difference_In_Days1 < 0 || Difference_In_Days2 < 0) { // negative total days (start date later than end date)
        document.getElementById("dvtextless0").style.display = "inline";
      } else if (Difference_In_Days1 > 0 && Difference_In_Days1 < 60 || Difference_In_Days2 > 0 && Difference_In_Days2 < 60) { // 0 < total days < 60
        document.getElementById("dvtextless60").style.display = "block";
      } else if (Difference_In_Days1 > 60 && Difference_In_Days1 <= 182 || Difference_In_Days2 > 60 && Difference_In_Days2 <= 182) { // 60 < total days < 182
        document.getElementById("dvtext61182").style.display = "block";
      } else if (Difference_In_Days1 > 182 || Difference_In_Days2 > 182) { // more than 182 days
        document.getElementById("dvtextmore183").style.display = "block";
      } else { //NaN (clicking Calculate without inputting dates)
        document.getElementById("dvtextNoStartDate").style.display = "inline";
        document.getElementById("dvtextNoEndDate").style.display = "block";
      }

      document.getElementById("numofdays").innerHTML = "Total Stay : " + Difference_In_Days1 && Difference_In_Days2;
      document.getElementById("displaystartend1").innerHTML = getFormattedDate(startDate1) + " to " + getFormattedDate(endDate1);
      document.getElementById("displaystartend1").innerHTML = getFormattedDate(startDate2) + " to " + getFormattedDate(endDate2);

    }

    function showArrDepDate() { // when Yes selected
      document.getElementById("dvPPbtn").style.display = "block";
    }

     function addDate1() { // when Yes selected
      document.getElementById("addDate1").style.display = "block";
    }

    function calculateDate() {
      var startDate1 = document.getElementById("startDate1").value;
      var endDate1 = document.getElementById("endDate1").value;
      var startDate2 = document.getElementById("startDate2").value;
      var endDate2 = document.getElementById("endDate2").value;
      var arrDate = document.getElementById("arrDate").value;
      var depDate = document.getElementById("depDate").value;
      var endToDep_Days1 = new Date(depDate).getTime() - new Date(endDate1).getTime();
      var endToDep_Days2 = new Date(depDate).getTime() - new Date(endDate2).getTime();
      var arrToStart_Days1 = new Date(startDate1).getTime() - new Date(arrDate).getTime();
      var arrToStart_Days2 = new Date(startDate2).getTime() - new Date(arrDate).getTime();
      var emp = new Date(endDate1).getTime() - new Date(startDate1).getTime();
      var emp = new Date(endDate2).getTime() - new Date(startDate2).getTime();
      var totalInDays1 = (arrToStart_Days1 + endToDep_Days1 + emp) / (1000 * 3600 * 24);
      var totalInDays2 = (arrToStart_Days2 + endToDep_Days2 + emp) / (1000 * 3600 * 24);
        if (totalInDays1 < 60 || totalInDays2 < 60) {
        document.getElementById("dvtextless60").style.display = "block";
      } else if (totalInDays1 > 60 && totalInDays1 <= 182 || totalInDays2 > 60 && totalInDays2 <= 182) {
        document.getElementById("dvtext61182").style.display = "block";
      } else {
        document.getElementById("dvtextmore183").style.display = "block";
      }

      document.getElementById("numofdays").innerHTML = "Total Stay and Presence : " + Total_In_Days1 && Total_In_Days2;
      document.getElementById("displaystartend1").innerHTML = getFormattedDate(arrDate) + " to " + getFormattedDate(depDate);
    }

    function resetForm() {
      document.getElementById('rCalculator').reset();
      location.reload();
    }

    function getFormattedDate(d) {
      return d.substr(8, 2) + "/" + d.substr(5, 2) + "/" + d.substr(0, 4)
    }
<style>
    body {
      font-family: Arial;
      padding: 20px;
      margin: 20px;
    }

    label {
      font-family: Arial;
    }

    input {
      font-family: Arial;
    }

    span {
      font-family: Arial;
    }

    .residencyResult {
      font-family: Arial;
    }
  </style>

<body>

  <h1>How long have you stayed here?</h1>
  <h2>When you start staying here<span style="color:red;">*</span></h2>
  <p style="color:red;">(from the latest to the earliest)</p>

  <form id="rCalculator">
    <pre>
<label><b>Start date of stay <span style="color:red;">*</span></b></label><br>
<input type="date" name="startDate" id="startDate" required/>
<small id="dvtextless0" style="display:none; color:red; font-family:Arial;">*Start date cannot be later than Last date.</small>
<small id="dvtextNoStartDate" style="display:none; color:red; font-family:Arial; font-size:13px;">*This field is required.</small>

<label><b>Last date of stay <span style="color:red;">*</span></b></label><br>
<input type="date" name="endDate" id="endDate" required/><br>
<small id="dvtextNoEndDate" style="display:none; color:red; font-family:Arial; font-size:13px;">*This field is required.</small>

<button type="button" id="add" onclick="addDate1();">Add</button>

<div class="addDate1" id="addDate1" style="display:none;">

<label><b>Start date of stay <span style="color:red;">*</span></b></label><br>
<input type="date" name="startDate" id="startDate" required/>
<small id="dvtextless0" style="display:none; color:red; font-family:Arial;">*Start date cannot be later than Last date.</small>
<small id="dvtextNoStartDate" style="display:none; color:red; font-family:Arial; font-size:13px;">*This field is required.</small>

<label><b>Last date of stay <span style="color:red;">*</span></b></label><br>
<input type="date" name="endDate" id="endDate" required/><br>
<small id="dvtextNoEndDate" style="display:none; color:red; font-family:Arial; font-size:13px;">*This field is required.</small>

</div>

<label for="Presence"><b>Were you physically present here before this?</b></label>

<input type="radio" value="Yes" name="radiobttn" id="Yes" style="font-family:Arial;" onclick="showArrDepDate();">Yes
<input type="radio" value="No" name="radiobttn" id="No" style="font-family:Arial;" onclick="calculateEmp();">No

<div class="physcialPresence" id="dvPPbtn" style="display:none;">

<label><b>Arrival Date <span style="color:red;">*</span></b></label><br>
<input type="date" name="arrDate" id="arrDate" required/>

<label><b>Departure Date <span style="color:red;">*</span></b></label><br>
<input type="date" name="depDate" id="depDate" required/>

</div>

<span id="numofdays"></span>

<span id="displaystartend1"></span>

<div class="residencyResult" id="dvtextless60" style="display:none; border:1px solid lightgray; border-radius:15px; padding:20px; background-color:#FFFAC7; margin:15px;">
<span style="font-size:18px"><b>Stay is too short</b></span>


</div>

<div class="residencyResult" id="dvtext61182" style="display:none; border:1px solid lightgray; border-radius:15px; padding:20px; background-color:#FFFAC7; margin:15px;">
<span style="font-size:18px"><b>This is still too short</b></span>


</div>

<div class="residencyResult" id="dvtextmore183" style="display:none; border:1px solid lightgray; border-radius:15px; padding:20px; background-color:#FFFAC7; margin:15px;">
<span style="font-size:18px"><b>Oh ok.. That's long enough</b></span>



</div>


<button type="button" id="calculate" onclick="calculateDate(); calculateEmp();">Calculate</button>   <button type="button" id="startover" onclick="resetForm();">Reset</button>
<head>
  <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tax Residency Calculator</title>

2 个答案:

答案 0 :(得分:2)

您当前的代码抛出了一些异常。快速浏览一下就会发现您的选择器不正确,例如 ID startDate1 不存在,而其他一些选择器也会失败。似乎您的大多数问题可能与您访问数据的方式有关,并且您没有考虑如果数据不存在会发生什么,例如,如果值为 null,您可能需要添加一些检查。

我不知道你为什么使用普通的 JavaScript,但有一些东西可以帮助你,比如 jQuery,也许还有用于日期处理的 Moment js。

我建议在本地的纯 HTML 文档或类似沙箱的 jsfiddle 中运行它,并注意错误,它们会让您对失败的地方有一个很好的了解。

我建议不要一直复制/粘贴,那样你可能会迷失于类和选择器。

编辑 1:

  • 您的代码不完整,HTML 不会关闭您的 pre 或表单标签。
  • 您在 HTML 中的 id 不正确,开始日期和结束日期都命名为 startDate 和 endDate,但您的 JS 正在调用 startDate1、endDate1、startDate2 和 endDate2。您需要更改这些名称。
  • 您的变量 totalInDays1 和 totalInDays2 与 JS 试图在您的 calculateDate 函数(Total_In_Days1 和 Total_In_Days2)中访问的内容不匹配
  • 您正在绑定访问 Difference_In_Time,但您只有 Difference_In_Time1 和 Difference_In_Time2,您需要在您定义 Difference_In_Days1 和 Difference_In_Days2 的 calculateEmp 中更改它。

在这些修复之后,您的代码将停止抛出错误。我会检查您的实施,并确保您在进行计算时访问正确的变量。

您的问题似乎是您复制了工作代码并进行了不完整的修改。如果您有工作代码的某个版本,我们或许可以帮助您将其调整到多个日期。

编辑 2 经过进一步检查,您似乎还遗漏了一些其他变量名称,例如 emp,您定义了两次,应该是 emp1 和 emp2。

我将创建一个接受两个日期的单独函数。

无论如何,我对您的函数 calculateDate 做了一些更改,试图不改变其当前行为,只是简单的旧重构。

function calculateEmp() {
  var startDate1 = document.getElementById("startDate1").value;
  var endDate1 = document.getElementById("endDate1").value;
  var startDate2 = document.getElementById("startDate2").value;
  var endDate2 = document.getElementById("endDate2").value;
  var dvtextless60 = document.getElementById("dvtextless60");
  var dvtext61182 = document.getElementById("dvtext61182");
  var dvtextmore183 = document.getElementById("dvtextmore183");
  var Difference_In_Time1 = new Date(endDate1).getTime() - new Date(startDate1).getTime();
  var Difference_In_Days1 = Difference_In_Time1 / (1000 * 3600 * 24);
  var Difference_In_Time2 = new Date(endDate2).getTime() - new Date(startDate2).getTime();
  var Difference_In_Days2 = Difference_In_Time2 / (1000 * 3600 * 24);

  if (Difference_In_Days1 < 0 || Difference_In_Days2 < 0) { // negative total days (start date later than end date)
    document.getElementById("dvtextless0").style.display = "inline";
  } else if (Difference_In_Days1 > 0 && Difference_In_Days1 < 60 || Difference_In_Days2 > 0 && Difference_In_Days2 < 60) { // 0 < total days < 60
    document.getElementById("dvtextless60").style.display = "block";
  } else if (Difference_In_Days1 > 60 && Difference_In_Days1 <= 182 || Difference_In_Days2 > 60 && Difference_In_Days2 <= 182) { // 60 < total days < 182
    document.getElementById("dvtext61182").style.display = "block";
  } else if (Difference_In_Days1 > 182 || Difference_In_Days2 > 182) { // more than 182 days
    document.getElementById("dvtextmore183").style.display = "block";
  } else { //NaN (clicking Calculate without inputting dates)
    document.getElementById("dvtextNoStartDate").style.display = "inline";
    document.getElementById("dvtextNoEndDate").style.display = "block";
  }

  document.getElementById("numofdays").innerHTML = "Total Stay : " + Difference_In_Days1 && Difference_In_Days2;
  document.getElementById("displaystartend1").innerHTML = getFormattedDate(startDate1) + " to " + getFormattedDate(endDate1);
  document.getElementById("displaystartend1").innerHTML = getFormattedDate(startDate2) + " to " + getFormattedDate(endDate2);

}

function showArrDepDate() { // when Yes selected
  document.getElementById("dvPPbtn").style.display = "block";
}

function addDate1() { // when Yes selected
  document.getElementById("addDate1").style.display = "block";
}

function calculateDate() {
  var startDate1 = document.getElementById("startDate1").value;
  var endDate1 = document.getElementById("endDate1").value;  
  
  var startDate2 = document.getElementById("startDate2").value;
  var endDate2 = document.getElementById("endDate2").value;
  
  var arrDate = document.getElementById("arrDate").value;
  var depDate = document.getElementById("depDate").value;
  
  var depDateTime = new Date(depDate).getTime();
  console.log("depDateTime", depDateTime);
  
  var arrDateTime = new Date(arrDate).getTime();
  console.log("arrDateTime", arrDateTime);
  
  var startDate1Time = new Date(startDate1).getTime();
  console.log("startDate1Time", startDate1Time);
  
  var endDate1Time = new Date(endDate1).getTime();
  console.log("endDate1Time", endDate1Time);
  
  var startDate2Time = new Date(startDate2).getTime();
  console.log("startDate2Time", startDate2Time);
  
  var endDate2Time = new Date(endDate2).getTime();  
  console.log("endDate2Time", endDate2Time);  
  
  var endToDep_Days1 = depDateTime - endDate1Time;
  console.log("endToDep_Days1", endToDep_Days1);
  
  var arrToStart_Days1 = startDate1Time - arrDateTime;
  console.log("arrToStart_Days1", arrToStart_Days1);
  
  var arrToStart_Days2 = startDate2Time - arrDateTime;
  console.log("arrToStart_Days2", arrToStart_Days2);
  
  var endToDep_Days2 = depDateTime - endDate2Time;
  console.log("endToDep_Days2", endToDep_Days2);
  
  var emp1 = endDate1Time - startDate1Time;
  console.log("emp1", depDateTime);
  
  var emp2 = endDate2Time - startDate2Time;
  console.log("emp2", depDateTime);  
  
  var totalInDays1 = (arrToStart_Days1 + endToDep_Days1 + emp1) / (1000 * 3600 * 24);
  var totalInDays2 = (arrToStart_Days2 + endToDep_Days2 + emp2) / (1000 * 3600 * 24);
  
  if (totalInDays1 < 60 || totalInDays2 < 60) {
    document.getElementById("dvtextless60").style.display = "block";
  } else if (totalInDays1 > 60 && totalInDays1 <= 182 || totalInDays2 > 60 && totalInDays2 <= 182) {
    document.getElementById("dvtext61182").style.display = "block";
  } else {
    document.getElementById("dvtextmore183").style.display = "block";
  }

  document.getElementById("numofdays").innerHTML = "Total Stay and Presence : " + (totalInDays1 + totalInDays2);
  document.getElementById("displaystartend1").innerHTML = getFormattedDate(arrDate) + " to " + getFormattedDate(depDate);
}

function resetForm() {
  document.getElementById('rCalculator').reset();
  location.reload();
}

function getFormattedDate(d) {
  return d.substr(8, 2) + "/" + d.substr(5, 2) + "/" + d.substr(0, 4)
}


function calculateTimeBetweenDates(startDate, encDate){
    var response = {
    ValidDate1: false,
    ValidDate2: false,
    
  };
}
 body {
      font-family: Arial;
      padding: 20px;
      margin: 20px;
    }

    label {
      font-family: Arial;
    }

    input {
      font-family: Arial;
    }

    span {
      font-family: Arial;
    }

    .residencyResult {
      font-family: Arial;
    }
<h1>How long have you stayed here?</h1>
<h2>When you start staying here<span style="color:red;">*</span></h2>
<p style="color:red;">(from the latest to the earliest)</p>

<form id="rCalculator">
        <label><b>Start date of stay <span style="color:red;">*</span></b></label>
        <br>
        <input type="date" name="startDate1" id="startDate1" required/>
        <small id="dvtextless0" style="display:none; color:red; font-family:Arial;">*Start date cannot be later than Last date.</small>
        <small id="dvtextNoStartDate" style="display:none; color:red; font-family:Arial; font-size:13px;">*This field is required.</small>

        <label><b>Last date of stay <span style="color:red;">*</span></b></label>
        <br>
        <input type="date" name="endDate1" id="endDate1" required/><br>
        <small id="dvtextNoEndDate" style="display:none; color:red; font-family:Arial; font-size:13px;">*This field is required.</small>
        <button type="button" id="add" onclick="addDate1();">Add</button>

        <div class="addDate1" id="addDate1" style="display:none;">
          <label><b>Start date of stay <span style="color:red;">*</span></b></label>
          <br>
          <input type="date" name="startDate2" id="startDate2" required/>
          <small id="dvtextless0" style="display:none; color:red; font-family:Arial;">*Start date cannot be later than Last date.</small>
          <small id="dvtextNoStartDate" style="display:none; color:red; font-family:Arial; font-size:13px;">*This field is required.</small>
          <label><b>Last date of stay <span style="color:red;">*</span></b></label>
          <br>
          <input type="date" name="endDate2" id="endDate2" required/><br>
          <small id="dvtextNoEndDate" style="display:none; color:red; font-family:Arial; font-size:13px;">*This field is required.</small>
        </div>

        <label for="Presence"><b>Were you physically present here before this?</b></label>
        <input type="radio" value="Yes" name="radiobttn" id="Yes" style="font-family:Arial;" onclick="showArrDepDate();">Yes
        <input type="radio" value="No" name="radiobttn" id="No" style="font-family:Arial;" onclick="calculateEmp();">No

        <div class="physcialPresence" id="dvPPbtn" style="display:none;">
          <label><b>Arrival Date <span style="color:red;">*</span></b></label>
          <br>
          <input type="date" name="arrDate" id="arrDate" required/>
          <label><b>Departure Date <span style="color:red;">*</span></b></label><br>
          <input type="date" name="depDate" id="depDate" required/>
        </div>

        <span id="numofdays"></span>

        <span id="displaystartend1"></span>

        <div class="residencyResult" id="dvtextless60" style="display:none; border:1px solid lightgray; border-radius:15px; padding:20px; background-color:#FFFAC7; margin:15px;">
          <span style="font-size:18px"><b>Stay is too short</b></span>
        </div>

        <div class="residencyResult" id="dvtext61182" style="display:none; border:1px solid lightgray; border-radius:15px; padding:20px; background-color:#FFFAC7; margin:15px;">
          <span style="font-size:18px"><b>This is still too short</b></span>
        </div>

        <div class="residencyResult" id="dvtextmore183" style="display:none; border:1px solid lightgray; border-radius:15px; padding:20px; background-color:#FFFAC7; margin:15px;">
          <span style="font-size:18px"><b>Oh ok.. That's long enough</b></span>
        </div>


        <button type="button" id="calculate" onclick="calculateDate(); calculateEmp();">Calculate</button>   <button type="button" id="startover" onclick="resetForm();">Reset</button>
</form>

此后,您可以在日志中看到,当您的函数尝试计算天数时,缺少一些内容。

答案 1 :(得分:-1)

您可以使用以下 JS 函数返回两个日期之间的总天数。

//startDate  = '2021-05-01' YYYY-MM-DD;
//endDate    = '2021-06-02' YYYY-MM-DD;
function total_days(start_date, end_Date) {
    const diffInMs = new Date(endDate) - new Date(startDate);
    //Converting milliseconds to days
    return (diffInMs / (1000 * 60 * 60 * 24));
}