2017-10-17 77 views
-1

對於Java程序,我需要2個日期的Timeperiod,但是我得到的Period.Class錯誤。日曆之間的Java期間

我試着用Period.between

 Calendar myCalendar = new GregorianCalendar(2017, Calendar.JANUARY,1); 
    Calendar myPeriod = new GregorianCalendar(2017, Calendar.MARCH, 1); 
    Period prd = Period.between(myCalendar, myPeriod); 
    return prd.getTime(); 

我用來返回myCalendar.getTime(); 現在我需要的myCalendarmyPeriod 「週期」 來獲得TIMEPERIOD。

謝謝。

+3

y有什麼錯誤你得到了嗎?該方法的簽名'between'示出,它預計LocalDates,不日程表 –

+0

在型週期(LOCALDATE,LOCALDATE)之間的方法是不適用於參數(日曆,日曆)用於錯誤 和 之間 在.getTime –

+0

上,類型Period的getTime()方法未定義您可以閱讀[如何將日曆轉換爲LocalDate](https://kodejava.org/how-do-i-convert-between-old-date-and -calendar-object-with-new-java-8-date-time /)或使用LocalDate的其他工廠方法。 –

回答

2

如果您使用的是Java 8,則Period接受2 LocalDate參數(在official documentation中閱讀更多關於它的內容)。

這是代碼,如果你還需要從CalendarLocalDate轉換:

Calendar myCalendar = new GregorianCalendar(2017, Calendar.JANUARY,1); 
Calendar myPeriod = new GregorianCalendar(2017, Calendar.MARCH, 1); 
LocalDate start = Instant.ofEpochMilli(myCalendar.getTimeInMillis()).atZone(ZoneId.systemDefault()).toLocalDate(); 
LocalDate end = Instant.ofEpochMilli(myPeriod.getTimeInMillis()).atZone(ZoneId.systemDefault()).toLocalDate(); 

否則,只需直接創建2個LocalDate變量:

LocalDate start = LocalDate.of(2017, Month.JANUARY, 1); 
LocalDate end = LocalDate.of(2017, Month.MARCH, 1); 

,然後計算它們之間的時間段:

Period prd = Period.between(start, end); 
System.out.println(prd.toString()); //P2M