1
我正在尝试为我的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;
}
}
如果您正在使用1990/05/06等本地日期,则无需转换为毫秒,这必然涉及考虑时区。 –
可能重复http://stackoverflow.com/questions/7103064/java-calculate-the-number-of-days-between-two-dates – Satya
@Satya这是一个可能的重复,但我怀疑OP正在尝试不使用Jodatime或其他库也可以 - 我假设是一个练习。 –