fork download
  1. import java.time.LocalDate;
  2. import java.time.temporal.ChronoUnit;
  3. import java.time.temporal.TemporalAdjusters;
  4.  
  5. public class Main {
  6. public static void main(String[] args) {
  7. // Test
  8. System.out.println(monthsBetween(LocalDate.of(2012, 1, 28), LocalDate.of(2012, 2, 1)));
  9. System.out.println(monthsBetween(LocalDate.of(2012, 2, 27), LocalDate.of(2012, 2, 28)));
  10. System.out.println(monthsBetween(LocalDate.of(2012, 3, 28), LocalDate.of(2012, 7, 1)));
  11. }
  12.  
  13. static int monthsBetween(final LocalDate fromDate, final LocalDate toDate) {
  14. return Math.toIntExact(
  15. ChronoUnit.MONTHS.between(
  16. fromDate.with(TemporalAdjusters.firstDayOfMonth()),
  17. toDate.with(TemporalAdjusters.firstDayOfMonth())
  18. )
  19. );
  20. }
  21. }
Success #stdin #stdout 0.07s 48904KB
stdin
Standard input is empty
stdout
1
0
4