Creates a new date object with the first date in the same season as the given date. - Java java.time

Java examples for java.time:LocalDate

Description

Creates a new date object with the first date in the same season as the given date.

Demo Code


//package com.java2s;

import java.time.LocalDate;

import java.time.Month;

import java.time.temporal.ChronoField;

public class Main {
    /**/*from  w ww  .  ja  v a  2 s  .c  o  m*/
     * 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);
        }
    }
}

Related Tutorials