JavaScript 如何检查日期是否早于1小时前
给定一个日期,任务是使用JavaScript检查给定的日期是否早于1小时前。
方法1
- 计算当前日期和之前日期之间的毫秒差。
- 如果大于1小时的毫秒数,则返回false,否则返回true。
示例: 这个示例实现了上述方法。
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 15px; font-weight: bold;">
</p>
<button onclick="gfg_Run()">
click here
</button>
<p id="GFG_DOWN" style="color:green;
font-size: 20px; font-weight: bold;">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
var prev_date = new Date();
var d = new Date();
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
prev_date.addHours(-2);
el_up.innerHTML = "Click on the button to "
+ "check if the date is less than "
+ "1 hour ago.<br>Previous date = "
+ prev_date;
function gfg_Run() {
// Hour in milliseconds
var ONE_HOUR = 60 * 60 * 1000;
if ((d - prev_date) < ONE_HOUR) {
el_down.innerHTML = "Date is less"
+ " than 1 hour ago.";
}
else {
el_down.innerHTML = "Date is not "
+ "less than 1 hour ago.";
}
}
</script>
HTML
输出:
方法2
- 从当前时间减去1小时的毫秒数。
- 比较当前日期和上一个日期的毫秒数。
- 如果这些毫秒数大于1小时的毫秒数,则返回false,否则返回true。
示例2: 这个示例使用如上所述的方法。
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 15px; font-weight: bold;">
</p>
<button onclick="gfg_Run()">
click here
</button>
<p id="GFG_DOWN" style="color:green;
font-size: 20px; font-weight: bold;">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
var prev_date = new Date();
var d = new Date();
const check = (date) => {
const HOUR = 1000 * 60 * 60;
const anHourAgo = Date.now() - HOUR;
return date > anHourAgo;
}
el_up.innerHTML = "Click on the button to check"
+ " if the date is less than 1 hour"
+ " ago.<br>Previous date = " + prev_date;
function gfg_Run() {
var c = check(prev_date);
if (c) {
el_down.innerHTML = "Date is less "
+ "than 1 hour ago.";
}
else {
el_down.innerHTML = "Date is not less"
+ " than 1 hour ago.";
}
}
</script>
HTML
输出: