首页javadateJava Data Type - 如何使用与指定日期相同的季节中的第一个日期来创建新日期

Java Data Type - 如何使用与指定日期相同的季节中的第一个日期来创建新日期

我们想知道如何使用与指定日期相同的季节中的第一个日期来创建新日期。

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

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