Java Data Type How to - Create a new date with the first date in the same season as the given date








Question

We would like to know how to create a new date with the first date in the same season as the given date.

Answer

A season is defined as a period from April to September and from October to March.

/**// ww  w.ja v  a2  s  .c  o m
 * This class provides some useful utility methods for date and time operations.
 * The implementations is done using the new date and time api in Java8.
 * 
 * @see add further links
 *
 * @author created: 7droids.org on 27.02.2014 20:45:58
 * @author last change: $Author: $ on $Date: $
 * @version $Revision: $
 */
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoField;

public class Main {
  public static void main(String[] argv) {
    System.out.println(beginOfSeason(LocalDate.now()));
  }


  /**
   * 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);
  }
  }
}

The code above generates the following result.