Java 8 提供了幾個方便的日期和時間工具類,通過它們可以很輕松的設定特定的日期和時間。
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.temporal.TemporalAdjusters; /** * 根據當前時間獲取特定的日期或時間 * 主要思路是使用 TemporalAdjusters 工具類獲取當前特定的日期,然后再通過 LocalDateTime.of 將特定的日期與特定的時間組合成最終的 LocalDateTime。 */ class Scratch { public static void main(String[] args) { LocalDate nowDate = LocalDate.now(); LocalDate firstDayOfYear = nowDate.with(TemporalAdjusters.firstDayOfYear()); LocalDate lastDayOfYear = nowDate.with(TemporalAdjusters.lastDayOfYear()); LocalDateTime firstDateOfYear = LocalDateTime.of(firstDayOfYear, LocalTime.MIN); LocalDateTime lastDateOfYear = LocalDateTime.of(lastDayOfYear, LocalTime.MAX); LocalDate firstDayOfMonth = nowDate.with(TemporalAdjusters.firstDayOfMonth()); LocalDate lastDayOfMonth = nowDate.with(TemporalAdjusters.lastDayOfMonth()); LocalDateTime firstDateOfMonth = LocalDateTime.of(firstDayOfMonth, LocalTime.MIN); LocalDateTime lastDateOfMonth = LocalDateTime.of(lastDayOfMonth, LocalTime.MAX); LocalDateTime fistDateOfDay = LocalDateTime.of(nowDate, LocalTime.MIN); LocalDateTime lastDateOfDay = LocalDateTime.of(nowDate, LocalTime.MAX); System.out.println("當前時間:" + LocalDateTime.now()); System.out.println("今年第一天:" + firstDateOfYear); System.out.println("今天最后一天:" + lastDateOfYear); System.out.println("當月第一天:" + firstDateOfMonth); System.out.println("當月最后一天:" + lastDateOfMonth); System.out.println("當天開始時間:" + fistDateOfDay); System.out.println("當天結束時間:" + lastDateOfDay); // print: // 當前時間:2020-04-17T10:10:40.443 // 今年第一天:2020-01-01T00:00 // 今天最后一天:2020-12-31T23:59:59.999999999 // 當月第一天:2020-04-01T00:00 // 當月最后一天:2020-04-30T23:59:59.999999999 // 當天開始時間:2020-04-17T00:00 // 當天結束時間:2020-04-17T23:59:59.999999999 } }