Creates a new date object with the last day of the season of the given date. - Java java.time

Java examples for java.time:Day

Description

Creates a new date object with the last day of the season of 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  ww  w. j  a  v a2  s . c  o m
     * 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);
        }
    }

    /**
     * Creates a new date object with the last day of the same month as the
     * given date.
     */
    public static LocalDate endOfMonth(LocalDate date) {
        return date.withDayOfMonth(date.lengthOfMonth());
    }
}

Related Tutorials