直接上代码
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);
}
}
该代码片段展示了如何使用Java 8的LocalDate和LocalDateTime类来获取指定年份和月份的第一天及最后一天、第一秒及最后一秒。这些方法包括firstDateOfYear(), lastDateOfYear(), firstDateOfMonth(), lastDateOfMonth(), firstTimeOfYear(), lastTimeOfYear(), firstTimeOfMonth()和lastTimeOfMonth(),它们提供了计算日期和时间边界值的简洁方式。
1328

被折叠的 条评论
为什么被折叠?



