Javascript比较两个日期来得到区别 [英] Javascript compare two dates to get a difference
问题描述
我想比较两个不同的日期,看看输入的日期是否是今天7天后。我已经做了一些谷歌搜索,并提出了这一点:
I am trying to compare two different dates to see if the date inputted is after 7 days of todays date. I have done a bit of googling and come up with this:
function val_date(input){
var date = new Date(input);
date = date.getTime() / 1000;
var timestamp = new Date().getTime() + (7 * 24 * 60 * 60 * 1000)
window.alert("Date: "+date + " = N_Date: "+timestamp);
if(timestamp > date || timestamp === date){
// The selected time is less than 7 days from now
return false;
}
else if(timestamp < date){
// The selected time is more than 7 days from now
return true;
}
else{
// -Exact- same timestamps.
return false;
}
}
我正在使用警报,进度以确保日期不同。警报的输出只是:
I am using an alert so that I can check my progress to make sure the dates are different. The output of the alert just says:
日期:NaN = N_Date = 13255772630(< - 或类似的东西) >
Date: NaN = N_Date = 13255772630 (<- or something like that).
有什么我在这里做错了吗?
不知道是否有帮助,但日期格式是 DD -MM-YYYY
Is there something I am doing wrong here?
Not sure if it helps but my date format is DD-MM-YYYY
推荐答案
如果您要比较日期并且不想包含时间,例如:
If you are comparing dates and don't want to include time, you can use something like:
// dateString is format DD-MM-YYYY
function isMoreThan7DaysHence(dateString) {
// Turn string into a date object at 00:00:00
var t = dateString.split('-');
var d0 = new Date(t[2], --t[1], t[0]);
// Create a date for 7 days hence at 00:00:00
var d1 = new Date();
d1.setHours(0, 0, 0, 0);
d1.setDate(d1.getDate() + 7);
return d0 >= d1;
}
请注意,今天的日期必须清零。
Note that the hours for today's date must be zeroed.
这篇关于Javascript比较两个日期来得到区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!