2016-04-27 52 views
0

與當前的日期進行比較我應該向用戶詢問他們的年齡,作爲回報,我應該檢查他們已經多少天住了。我試過在這裏搜索,但我無法完全知道如何去做。公曆沒有外部類

條件:將GregorianCalendar日期作爲參數並返回該日期和今天之間的天數差的方法。 我無法爲此使用任何外部類。

這是我未完成的代碼:

public static void main(String[] args) { 
    int day; 
    int month; 
    int year; 
    int difference; 
    Scanner scanIn = new Scanner(System.in); 

    System.out.println("Please enter your birth date."); 
    System.out.println("Please enter the month you were born in (mm)"); 
    month = scanIn.nextInt(); 
    System.out.println("Please enter the day you were born in (dd)"); 
    day = scanIn.nextInt(); 
    System.out.println("Please enter the year you were born in (yyyy)"); 
    year = scanIn.nextInt(); 

    GregorianCalendar greg = new GregorianCalendar(year, month, day); 

    difference = getDifference(greg); 
    month = greg.get(Calendar.MONTH) + 2; 
    year = greg.get(Calendar.YEAR); 

    //System.out.println("Year is " + year); 
    //System.out.println("Month " + month); 

} 

public static int getDifference(GregorianCalendar greg) { 
    Calendar now = new GregorianCalendar(); 
    int difference; 
    System.currentTimeMillis.greg(); 

    difference = greg - now; 
    return difference; 
} 

我不明白怎麼去區別呢?

我的教練建議我們用毫秒來解決這個問題,但我已經花了4小時試圖解決這個問題,我不明白這一點。

我如何得到當前的日,月和年?

+0

在發佈之前請耐心搜索Stack Overflow。 –

回答

1

建議使用Java中8,而不是Calendar API的new date API。特別是,您可以使用here所述的方法ChronoUnits.DAYS.between()。我的建議是:

LocalDate dob = LocalDate.of(year, month, day); 
    LocalDate now = LocalDate.now(); 
    difference=(int)ChronoUnit.DAYS.between(dob, now); 

    System.out.println("Days since date of birth: " + difference); 

您可以方便地查看是給出了相同的結果比舊的接口:

GregorianCalendar greg = new GregorianCalendar(year, month-1, day); 
    Calendar nowCal = new GregorianCalendar();  
    long deltaMillis = nowCal.getTime().getTime() - greg.getTime().getTime(); 

    System.out.println("Days since date of birth: " + deltaMillis/(1000*60*60*24)); 

注意,Calendar接口從0開始,在新的API計數個月從1開始。

我希望它有幫助。

+1

日曆已棄用?查看Java8的Calendar API https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html。 – Unknown

+0

不,你說得對,謝謝。 – joel314

+1

儘管沒有正式棄用,但java.util.Date/.Calendar類遭受糟糕的設計,現在已經成爲遺留的,被java.time類取代。甲骨文解釋[這裏](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html) –

1

如果只能使用GregorianCalendar,一種方法是將日曆的兩個實例轉換爲它們的毫秒錶示,通過getTimeInMillis,減去它們,然後計算通過除以(24 * 60 * 60 * 1000)。

例如:

public static int countDaysSince(GregorianCalendar pastDate) { 
    GregorianCalendar now = GregorianCalendar.getInstance(); 

    long difference = pastDate.getTimeInMillis() - now.getTimeInMillis(); 
    return difference/(24 * 60 * 60 * 1000); // 24 hours, 60 minutes, 60 seconds, 1000 milliseconds 
} 

應該這樣做。