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或其他庫也可以 - 我假設是一個練習。 –