我正在尝试修改一个程序,以便我介绍java课程。用户以下列格式(19900506)输入他们的生日,然后显示该人的天数。该程序使用GregorianCalendar类来获取今天的日期并比较两者。闰年被考虑在内。我能够正确的程序,但我需要编写另一个版本,使用我自己的算法计算差异。我碰到了墙,无法弄清楚如何做到这一点。我想将两个日期之间的差异转换为毫秒,然后再转换为几天。但是有很多事情需要考虑,比如几个月的日子,从今天开始的日子等等。任何帮助都会受到赞赏。
这是我的代码:
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class DayssinceBirthV5 {
public static void main(String[] args) {
GregorianCalendar greg = new GregorianCalendar();
int year = greg.get(Calendar.YEAR);
int month = greg.get(Calendar.MONTH);
int day = greg.get(Calendar.DAY_OF_MONTH);
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your birthday: AAAAMMDD): ");
int birthday = keyboard.nextInt();//
int testyear = birthday / 10000;// year
int testmonth = (birthday / 100) % 100;// Month
int testday = birthday % 100;// Day
int counter = calculateLeapYears(year, testyear);
GregorianCalendar userInputBd = new GregorianCalendar(testyear, testmonth - 1, testday);// Input
long diffSec = (greg.getTimeInMillis() - userInputBd.getTimeInMillis());// Räkna ut diff
// long diffSec = greg.get(Calendar.YEAR)-birthday;//calc Diff
long total = diffSec / 1000 / 60 / 60 / 24;// calc dif in sec. Sec/min/hours/days
total += counter;
System.out.println("Today you are : " + total + " days old");
}
private static int calculateLeapYears(int year, int testyear) {
int counter = 0;
for (int i = testyear; i < year; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
counter++;
System.out.println("Amount of leap years: " + counter);
}
}
return counter;
}
}
答案 0 :(得分:3)
你可以计算这样的天数 -