溫馨提示×

java如何獲取零點時間

小億
87
2024-09-05 06:33:55
欄目: 編程語言

在Java中,要獲取當天零點時間(即00:00:00),可以使用java.time包中的LocalDateTimeZoneId類。以下是一個示例:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        // 獲取當前日期
        LocalDateTime now = LocalDateTime.now();
        
        // 將當前日期設(shè)置為零點時間
        LocalDateTime midnight = now.withHour(0).withMinute(0).withSecond(0).withNano(0);
        
        // 獲取系統(tǒng)默認時區(qū)
        ZoneId zoneId = ZoneId.systemDefault();
        
        // 將零點時間轉(zhuǎn)換為ZonedDateTime對象
        ZonedDateTime zonedDateTime = midnight.atZone(zoneId);
        
        // 輸出零點時間
        System.out.println("零點時間: " + zonedDateTime);
    }
}

這段代碼首先獲取當前日期,然后將其設(shè)置為零點時間(00:00:00)。接著,它獲取系統(tǒng)默認時區(qū),并將零點時間轉(zhuǎn)換為ZonedDateTime對象。最后,輸出零點時間。

0