-1

For a Java program, I need a Timeperiod from 2 Dates but i get Errors with the Period.Class.

I tried to get the TimePeriod with 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();

I used to return myCalendar.getTime(); Now I need the "Period" of myCalendar and myPeriod.

Thank you.

sheldonzy
  • 5,505
  • 9
  • 48
  • 86
  • 3
    What errors do you get? The signature of the method `between` shows that it expects LocalDates, not Calendar – Malte Hartwig Oct 17 '17 at 10:10
  • The method between(LocalDate, LocalDate) in the type Period is not applicable for the arguments (Calendar, Calendar) for the Error in between and The method getTime() is undefined for the type Period on .getTime – David Khano Oct 17 '17 at 10:12
  • You can read [how to convert calendar to LocalDate](https://kodejava.org/how-do-i-convert-between-old-date-and-calendar-object-with-the-new-java-8-date-time/) or use the other factory methods of LocalDate. – Malte Hartwig Oct 17 '17 at 10:14
  • 1
    @DavidKhano As the compiler states, `between()` expects arguments of type `LocalDate` not `Calender`. Also, there is not `getTime()` method in `Period` class [for reference](https://docs.oracle.com/javase/8/docs/api/java/time/Period.html) – Sridhar Oct 17 '17 at 10:18
  • @DavidKhano please [refer this](https://stackoverflow.com/questions/30833582/how-to-calculate-the-number-of-days-in-a-period) to understand how period works. – Sridhar Oct 17 '17 at 10:21

1 Answers1

2

If you are using Java 8, the Period accepts 2 LocalDate parameters (read more about it in the official documentation).

This is the code if you still need the conversion from Calendar to LocalDate:

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();

Otherwise, just create the 2 LocalDate variables directly:

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

And then calculate the period between them:

Period prd = Period.between(start, end);
System.out.println(prd.toString()); //P2M
aUserHimself
  • 1,589
  • 2
  • 17
  • 26