首页 > 解决方案 > 如何计算日期并使用输入字段显示剩余日期?

问题描述

我想来一个代码,显示某个日期仍然有效以及持续多长时间。

到目前为止我提出的代码可以检查日期是否不在未来。但我不知道日期是否仍然有效。有人能帮我吗?

function TheorieFunction() {
  var startDate = new Date(document.getElementById('DateTheorie').value);
  var today = new Date();

  if (startDate.getTime() > today.getTime()) {
    alert("Error: Given date is in the future");
  }
  if (startDate.getTime() > today.get(Calendar.YEAR) - 3) {
    document.getElementById("Theorietxt").innerHTML = "Your theorie is still valid for" + today.getTime() - startDate.getTime()
    "days";
  } else {
    document.getElementById("Theorietxt").innerHTML = "Your theorie is invalid";
  }
}
Date theorie exam: <input type="date" id="DateTheorie" value="2017-01-01">
<span class="validity"></span>
<button id=Btntheorie onclick="TheorieFunction()">Check</button>

<p id="Theorietxt"></p>

标签: javascripthtml

解决方案


您是否正在寻找这样的解决方案?利用这篇文章中的日期差异功能

编辑:我只使用了基本的年差计算,比如每年 356 天。如果您想要确切的年份差异,则需要使用moment.js 差异功能

您可以在此小提琴中使用 moment js 找到实现

function TheorieFunction() {
    var startDate = new Date(document.getElementById('DateTheorie').value);
    var today = new Date();

    if (startDate.getTime() > today.getTime()) {
        alert("Error: Given date is in the future");
        return;
    }            
    if(startDate.valueOf() !== NaN) {
        const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
        const diffDays = Math.round(Math.abs((today - startDate) / oneDay));
        if (diffDays < 3 * 365) {
            document.getElementById("Theorietxt").innerHTML="Your theorie is still valid for" + (diffDays) +  "days";
        }
        else {
            document.getElementById("Theorietxt").innerHTML="Your theorie is invalid";
        }
    } else {
        alert('In Valid Date selected');
    }
}
Date theorie exam: <input type="date" id="DateTheorie" value="2020-01-01" />
<span class="validity"></span>
<button id="Btntheorie" onclick="TheorieFunction()">Check</button>
<p id="Theorietxt"></p>


推荐阅读