Java Data Type How to - Create a new date object with the last day of the season of the given date








Question

We would like to know how to create a new date object with the last day of the season of the given date.

Answer

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoField;
/*from   ww  w .  j ava 2  s  . c om*/
public class Main {
  public static void main(String[] argv) {
    System.out.println(endOfSeason(LocalDate.now()));
  }

  /**
   * Creates a new date object with the last day of the season of the given
   * date. The time is set to 0 o'clock.
   */
  public static LocalDate endOfSeason(LocalDate date) {
    LocalDate result = beginOfSeason(date);
    return endOfMonth(result.plusMonths(5));
  }

  /**
   * Creates a new date object with the first date in the same season as the
   * given date. A season is defined as a period from April to September and
   * from October to March.
   */
  public static LocalDate beginOfSeason(LocalDate date) {
    int nMonth = date.get(ChronoField.MONTH_OF_YEAR);
    switch (Month.of(nMonth)) {
    case JANUARY:
    case FEBRUARY:
    case MARCH:
      // Jan-Mar --> move to the previous year 1. October
      return date.minusMonths(
          nMonth + Month.DECEMBER.getValue() - Month.OCTOBER.getValue())
          .withDayOfMonth(1);
    case APRIL:
    case MAY:
    case JUNE:
    case JULY:
    case AUGUST:
    case SEPTEMBER:
      // Apr-Sep --> move to 1. April
      return date.minusMonths(nMonth - Month.APRIL.getValue())
          .withDayOfMonth(1);
    default:
      // Oct-Dec --> move to 1. October
      return date.minusMonths(nMonth - Month.OCTOBER.getValue())
          .withDayOfMonth(1);
    }
  }

  public static LocalDate endOfMonth(LocalDate date) {
    return date.withDayOfMonth(date.lengthOfMonth());
  }

}

The code above generates the following result.