fork(1) download
  1. import java.text.ParseException;
  2. import java.text.SimpleDateFormat;
  3. import java.time.ZoneOffset;
  4. import java.time.ZonedDateTime;
  5. import java.time.temporal.ChronoUnit;
  6. import java.time.temporal.TemporalAdjusters;
  7. import java.util.Date;
  8. import java.util.Locale;
  9. import java.util.TimeZone;
  10.  
  11. public class Main {
  12. public static void main(String[] args) throws ParseException {
  13. // Test
  14. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
  15. sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
  16.  
  17. System.out.println(monthsBetween(sdf.parse("2012-01-28"), sdf.parse("2012-02-01")));
  18. System.out.println(monthsBetween(sdf.parse("2012-02-27"), sdf.parse("2012-02-28")));
  19. System.out.println(monthsBetween(sdf.parse("2012-03-28"), sdf.parse("2012-07-01")));
  20. }
  21.  
  22. static int monthsBetween(final Date fromDate, final Date toDate) {
  23. ZonedDateTime zdtFrom = fromDate.toInstant().atZone(ZoneOffset.UTC);
  24. ZonedDateTime zdtTo = toDate.toInstant().atZone(ZoneOffset.UTC);
  25.  
  26. return Math.toIntExact(
  27. ChronoUnit.MONTHS.between(
  28. zdtFrom.with(TemporalAdjusters.firstDayOfMonth()),
  29. zdtTo.with(TemporalAdjusters.firstDayOfMonth())
  30. )
  31. );
  32. }
  33. }
Success #stdin #stdout 0.16s 56048KB
stdin
Standard input is empty
stdout
1
0
4