最近一直使用LocalDateTime,總是忘記怎麼轉換,僅此記錄一下java
import java.time.Instant; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; public class Test { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); System.out.println("當前時間: "+now); //時間格式 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println("formate: "+ now.format(formatter)); //當天的零點 System.out.println("當天的零點: "+LocalDateTime.of(now.toLocalDate(), LocalTime.MIN)); //當天的最後時間 System.out.println("當天的最後時間: "+LocalDateTime.of(now.toLocalDate(), LocalTime.MAX)); //最近的五分鐘點位 Integer minute = now.getMinute(); minute = minute/5*5; System.out.println("最近的五分鐘點位: "+LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), now.getHour(), minute, 0)); //Date轉爲LocalDateTime Date date = new Date(); Instant instant = date.toInstant(); ZoneId zoneId = ZoneId.systemDefault(); System.out.println("Date轉爲LocalDateTime: "+instant.atZone(zoneId).toLocalDateTime()); } }