我需要知道邮件写了多长时间。
window.date = function (o){
var r = new Date('1970-01-31 23:59:59').getTime();
var a = new Date().getTime()-new Date(o).getTime();
/*o=the date of the message: 2017-04-18 17:00:00*/
if(new Date().getFullYear()>new Date(o).getFullYear()){
n = 'more than a year ago';
}else if(new Date().getMonth()>new Date(o).getMonth()){
if(j=>r){
n = 'less than a month ago';
}else{
n = 'more than a month ago';
}
}else{
n = 'error'
}
问题是这些: 1)如果你在31/03写了一条消息,你会在一天(01/04)之后看到:'超过一个月前'(距离约会仅一天) 2)如果你在17/04和今天(18/04)写了一条消息,你试着读你不读'不到一个月前',但你看了'错误'。 我真的尝试过,但在这个页面中我没有阅读解决方案:https://www.w3schools.com/jsref/jsref_obj_date.asp 你能告诉我一个假设的解决方案吗?
答案 0 :(得分:1)
只需减去您今天要检查的时间,并将其与您检查的日期进行比较。如果您检查的日期早于结果,那么它已超过"该时间量"前。
此功能可能如下所示:
function checkDate(o) {
var today = new Date();
var dateToCheck = new Date(o);
var monthAgo = new Date(); monthAgo.setMonth(today.getMonth() - 1);
var yearAgo = new Date(); yearAgo.setFullYear(today.getFullYear() - 1);
if (dateToCheck < yearAgo) {
return "Over a year ago.";
} else if (dateToCheck < monthAgo) {
return "Over a month ago.";
} else {
return "Less than a month ago."
}
}
以下是其使用示例:
function checkDate(o) {
var today = new Date();
var monthAgo = new Date();
monthAgo.setMonth(today.getMonth() - 1);
var yearAgo = new Date();
yearAgo.setFullYear(today.getFullYear() - 1);
var dateToCheck = new Date(o);
if (dateToCheck < yearAgo) {
return "Over a year ago.";
} else if (dateToCheck < monthAgo) {
return "Over a month ago.";
} else {
return "Less than a month ago."
}
}
alert(checkDate(new Date(prompt("Enter a date (mm/dd/yyyy)"))));
&#13;