我正在尝试比较两个不同的日期,看看输入的日期是否在今天的7天之后。我做了一些谷歌搜索并提出了这个:
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;
}
}
我正在使用提醒,以便我可以检查我的进度以确保日期不同。警报的输出只是说:
日期:NaN = N_Date = 13255772630(&lt; - 或类似的东西)。
我在这里做错了吗? 不确定是否有帮助,但我的日期格式为 DD-MM-YYYY
答案 0 :(得分:4)
如果您要比较日期而不想包含时间,可以使用以下内容:
// 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;
}
请注意,今天的日期必须归零。
答案 1 :(得分:2)
日期:NaN
因为您传递给日期的字符串无法创建日期
Date.prototype.addDays = function (days) {
this.setDate(this.getDate() + days);
return this;
};
function val_date(input) {
var inputDate = new Date(input);
var dateWeek = new Date().addDays(7);
console.log(inputDate, dateWeek);
if (inputDate < dateWeek) {
// The selected time is less than 7 days from now
return false;
} else {
// The selected time is more than 7 days from now
return true;
}
}
答案 2 :(得分:0)
使用moment.js:
moment([2013, 2, 29]).fromNow();
答案 3 :(得分:0)
答案 4 :(得分:0)
假设输入是有效的Javascript Date对象,您可以尝试:
function dateDifference(oldDate) {
var currentDate = new Date();
var difference = currentDate - oldDate; //unit: milliseconds
var numDays = 7;
var threshHoldTime = numDays * (24 * 60 * 60 * 1000); //seven days in milliseconds
if (difference > threshHoldTime ) {
console.log("The difference is greateer then then 7 days");
}
else {
console.log("the date is not enough: " + difference);
}
}
答案 5 :(得分:0)
试试这个
var date = new Date(input).getTime(); // Get the milliseconds
var today = new Date();
//You can't compare date,
//so convert them to milliseconds
today = new Date(today.setDate(today.getDate() + 7)).getTime();
if (inputDate < today) {
// The selected time is less than 7 days from now
return false;
} else if{ ()
// -Exact- same timestamps.
return false;
}
else {
// The selected time is more than 7 days from now
return true;
}