java获取指定年(月)的第一天(秒)和最后一天(秒)
-
public class LocalDateUtil { public static void main(String[] args) { System.out.println("firstDateOfYear: " + firstDateOfYear(2023)); System.out.println("lastDateOfYear: " + lastDateOfYear(2023)); System.out.println("firstDateOfMonth: " + firstDateOfMonth(2023, 2)); System.out.println("lastDateOfMonth: " + lastDateOfMonth(2023, 2)); System.out.println("firstTimeOfYear: " + firstTimeOfYear(2023)); System.out.println("lastTimeOfYear: " + lastTimeOfYear(2023)); System.out.println("firstTimeOfMonth: " + firstTimeOfMonth(2023, 2)); System.out.println("lastTimeOfMonth: " + lastTimeOfMonth(2023, 2)); } /** * 指定年份的第一天 * * @param year 年份 */ public static LocalDate firstDateOfYear(int year) { return LocalDate.ofYearDay(year, 1); } /** * 指定年份的最后一天(用指定年份的第一天加1年,再减去1天) * * @param year * @return */ public static LocalDate lastDateOfYear(int year) { return firstDateOfYear(year).plusYears(1).minusDays(1); } /** * 指定年月的第一天 * * @param year 年份 * @param month 月份 */ public static LocalDate firstDateOfMonth(int year, int month) { return LocalDate.of(year, month, 1); } /** * 指定年月的最后一天(用指定年月的第一天加1月,再减去1天) * * @param year 年份 * @param month 月份 */ public static LocalDate lastDateOfMonth(int year, int month) { return firstDateOfMonth(year, month).plusMonths(1).minusDays(1); } /** * 指定年份的第一秒 * * @param year * @return */ public static LocalDateTime firstTimeOfYear(int year) { return LocalDateTime.of(LocalDate.ofYearDay(year, 1), LocalTime.MIN); } /** * 指定年份的最后一秒(用指定年份的第一秒加1年,再减去1秒) * * @param year * @return */ public static LocalDateTime lastTimeOfYear(int year) { return firstTimeOfYear(year).plusYears(1).minusSeconds(1); } /** * 指定年月的第一秒 * * @param year 年份 * @param month 月份 */ public static LocalDateTime firstTimeOfMonth(int year, int month) { return LocalDateTime.of(LocalDate.of(year, month, 1), LocalTime.MIN); } /** * 指定年月的最后一秒(用指定年月的第一秒加1月,再减去1秒) * * @param year 年份 * @param month 月份 */ public static LocalDateTime lastTimeOfMonth(int year, int month) { return firstTimeOfMonth(year, month).plusMonths(1).minusSeconds(1); } }