-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.

5
  • 3
    What errors do you get? The signature of the method between shows that it expects LocalDates, not Calendar Oct 17, 2017 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 Oct 17, 2017 at 10:12
  • You can read how to convert calendar to LocalDate or use the other factory methods of LocalDate. Oct 17, 2017 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
    – Sridhar
    Oct 17, 2017 at 10:18
  • @DavidKhano please refer this to understand how period works.
    – Sridhar
    Oct 17, 2017 at 10:21

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.