2015-09-05 96 views
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; 
    } 

} 
+0

如果您正在使用1990/05/06等本地日期,則無需轉換爲毫秒,這必然涉及考慮時區。 –

+0

可能重複http://stackoverflow.com/questions/7103064/java-calculate-the-number-of-days-between-two-dates – Satya

+0

@Satya這是一個可能的重複,但我懷疑OP正在嘗試不使用Jodatime或其他庫也可以 - 我假設是一個練習。 –

回答

2

可以計算的天像這樣的數字 -

  1. 編寫發現在一年的天數的方法:閏年有366天,非閏年有365.
  2. 寫另一種獲取日期並找到年份的方法 - 1月1日是第1天,1月2日是第2天,以此類推。您必須使用1.
  3. 計算以下內容:
    從出生之日起至年底的天數。
    從開始到當前日期的天數。
    所有年份之間的天數。
  4. 綜上所述。
+0

這真的是最好的方式嗎? – dwjohnston