使用Java 8引入的日期和时间类java.time.LocalDate、java.time.LocalDateTime和java.time.LocalTime,获取当前月第一天和当前月最后一天。
1.获取当前月第一天
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalDateTime firstDayOfMonth = getFirstDayOfMonth();
System.out.println("当前月份的第一天 00:00:00:");
System.out.println("日期和时间: " + firstDayOfMonth);
}
public static LocalDateTime getFirstDayOfMonth() {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 获取当前月份的第一天
LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1);
// 构造时间为 00:00:00
LocalTime startTime = LocalTime.of(0, 0, 0);
// 组合日期和时间
LocalDateTime firstDayOfMonthStart = LocalDateTime.of(firstDayOfMonth, startTime);
return firstDayOfMonthStart;
}
}
当前月最后一天
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
public class Main {
public static void main(String[] args) {
LocalDateTime lastDayOfMonth = getLastDayOfMonth();
System.out.println("当前月份的最后一天 23:59:59:");
System.out.println("日期和时间: " + lastDayOfMonth);
}
public static LocalDateTime getLastDayOfMonth() {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 获取当前月份
Month currentMonth = currentDate.getMonth();
// 获取当前月份的下一个月份
Month nextMonth = currentMonth.plus(1);
// 获取下一个月份的第一天
LocalDate firstDayOfNextMonth = LocalDate.of(currentDate.getYear(), nextMonth, 1);
// 前一天即为当前月份的最后一天
LocalDate lastDayOfMonth = firstDayOfNextMonth.minusDays(1);
// 构造时间为 23:59:59
LocalTime endTime = LocalTime.of(23, 59, 59);
// 组合日期和时间
LocalDateTime lastDayOfMonthEnd = LocalDateTime.of(lastDayOfMonth, endTime);
return lastDayOfMonthEnd;
}
}