javascript - 如何计算日期并使用输入字段显示剩余日期?
问题描述
我想来一个代码,显示某个日期仍然有效以及持续多长时间。
到目前为止我提出的代码可以检查日期是否不在未来。但我不知道日期是否仍然有效。有人能帮我吗?
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>
解决方案
您是否正在寻找这样的解决方案?利用这篇文章中的日期差异功能
编辑:我只使用了基本的年差计算,比如每年 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>
推荐阅读
- python - 在 python pandas 中使用 read_csv 忽略回车符(u1000D)
- python - 将字典传递给具有解包参数的函数
- sql - Oracle过程从查询结果中插入多行
- javascript - 似乎无法将 React 自定义钩子的返回直接传递给 React 上下文
- razor - Razor组件按钮@onclick不调用c#方法
- python-3.x - Pandas groupby时间戳并增加计数
- haproxy - 为什么我的 Haproxy 统计 GUI 限制会话在后端坚持 20000?
- html - HTML图像未加载图像src
- r - openxlsx在writeData()中的多行中重复一个字符串?
- .net - 使用特定的 Angular 版本创建一个新的“dotnet new angular --name test”