我希望能够计算考虑闰年的确切年龄天数。我在网上进行了研究,并找到了一些教程,但是考虑到闰年准确计算日期差异的教程似乎是链接[1]中的“最佳答案”,链接为:https://answers.yahoo.com/question/index?qid=20110629162003AAof4mT。我分析了代码,但有两个问题:
1)为什么在“计算生命天数”部分下面写入“days = days + leapYears”;
2)最后,在主方法中如何输入生日日期(以日、月和年表示)和当前日期(以日、月和年表示),并在其中查找这两个日期之间的天数差异?非常感谢您的帮助。提前致谢!
注:为方便起见,我已经包含了上述链接中的代码。
1)为什么在“计算生命天数”部分下面写入“days = days + leapYears”;
2)最后,在主方法中如何输入生日日期(以日、月和年表示)和当前日期(以日、月和年表示),并在其中查找这两个日期之间的天数差异?非常感谢您的帮助。提前致谢!
注:为方便起见,我已经包含了上述链接中的代码。
public class Days {
static int leapYear(int year) {
int leap;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
leap = 1;
}
else {
leap = 0;
}
return leap;
}
static int daysBefore(int month, int day, int year){
int days = 0;
int monthDays[] = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (leapYear(year) == 1){
monthDays[1] = 29;
}
for (int b = 0; b < month - 1; b++){
days = days + monthDays[b];
}
days = days + day;
return days;
}
public static void main(String[] args) {
//Birth date
int birthMonth = 0;
int birthDay = 0;
int birthYear = 0;
//Due date
int dueMonth = 0;
int dueDay = 0;
int dueYear = 0;
//(1) Calculate years lived
int yearsLived = dueYear - birthYear + 1;
//(2) Calculate leap years
int leapYears = 0;
for (int year = birthYear; year < dueYear+1; year++)
{
leapYears = leapYears + leapYear(year);
}
//(3) Calculate the number of days in your birth year before birth
int daysBeforeBirth = daysBefore(birthMonth, birthDay, birthYear);
//(4) Calculate the number of days remaining in the current year after the due date
int daysRemaining = 365 - daysBefore(dueMonth, dueDay, dueYear);
//Calculate days lived
int days = 0;
days = days + (365 * yearsLived);
days = days + leapYears;
days = days - daysBeforeBirth;
days = days - daysRemaining;
}
}