我正在尝试编写一个函数,该函数在给定过去的日期时将以滴加余数的方式计算年,月和日。与“2年1个月3天”一样,不是所有3种格式的总时间(2年= 24个月= 730天)。
码:
//Function to tell years/months/days since birthday to today
var ageID = function(date){
var nowDate = new Date();
//current date
var nowYear = nowDate.getFullYear();
var nowMonth = nowDate.getMonth();
var nowDay = nowDate.getDay();
//input birthday
var year = date[0];
var month = date[1];
var day = date[2];
var longMonth = [1, 3, 5, 7, 8, 10, 12];
var shortMonth = [4, 6, 9, 11];
var febMonth = [2];
var specfMonth = 0;
//finding month that corresponds to 28, 30, or 31 days in length
for (i = 0; i < longMonth.length; i++){
if (longMonth[i] === month){
specfMonth = 31;
}
}
for (i = 0; i < shortMonth.length; i++){
if (shortMonth[i] === month){
specfMonth = 30;
}
}
for (i = 0; i < febMonth.length; i++){
if (febMonth[i] === month){
specfMonth = 28;
}
}
//Reduced input and current date
var redYear = nowYear - year - 1;
var redMonth = 0;
var redDay = 0;
//The following 2 if/else are to produce positive output instead of neg dates.
if (nowMonth < month){
redMonth = month - nowMonth;
}else{
redMonth = nowMonth - month;
}
if (nowDay < day){
redDay = day - nowDay;
}else{
redDay= nowDay - day;
}
var adjMonth = 12 - redMonth;
var adjDay = specfMonth - redDay;
if (redYear < 1){
return adjMonth + " months, " + adjDay + " days ago.";
}else{
return redYear + " years, " + adjMonth + " months, " + adjDay + " days ago.";
}
};
console.log(ageID([2001, 9, 11]));
输出:
13 years, 10 months, 20 days ago.
但是,准确的输出将是:
13 years, 10 months, 30 days ago.
最佳答案
您的问题是:var nowDay = nowDate.getDay();
您应该使用:nowDate = nowDate.getDate();
代替。getDay()
返回一周中的天数。
星期一是“1”,星期二是“2”,依此类推。