Java8提供了新的時間接口LocalDateTime。本文主要介紹了Java8中LocalDateTime的一些常用操作方法。不多說,直接上代碼。欲知詳情,可以看看官網。
LocalDateTime localDateTime = LocalDateTime.now(); //時間運算,相加相減 System.out.println(localDateTime.plusYears(2)); //加2年 System.out.println(localDateTime.plusDays(2)); //加兩天 System.out.println(localDateTime.minusYears(2)); //減兩年 System.out.println(localDateTime.minusDays(2)); //減兩天 System.out.println(localDateTime.toString()); // 轉字符串 結果:2021-11-24T15:36:12.914 System.out.println(localDateTime.toLocalDate()); //獲取日期(LocalDate) 結果:2021-11-24 System.out.println(localDateTime.toLocalTime()); //獲取時間(LocalTime) 結果:15:36:12.914 System.out.println(localDateTime.getDayOfMonth()); //獲取當前時間月份的第幾天 結果:24 System.out.println(localDateTime.getDayOfWeek()); //獲取當前周的第幾天 結果:WEDNESDAY System.out.println(localDateTime.getDayOfYear()); //獲取當前時間在該年屬於第幾天 結果:328 System.out.println(localDateTime.getMonthValue()); // 獲取當前時間的月份(阿拉伯文) 結果:11 System.out.println(localDateTime.getMonth()); // 獲取當前時間的月份(英文) 結果:11 System.out.println(localDateTime.getHour()); // 獲取當前時間的小時數 結果:15 System.out.println(localDateTime.getMinute()); // 獲取當前時間的分鍾數 結果:36 //格式化輸出 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY/MM/dd HH:mm:ss"); System.out.println(localDateTime.format(formatter)); // 結果:2021/11/24 15:36:12 //構造時間 LocalDateTime startTime = LocalDateTime.of(2021, 1, 1, 20, 31, 20); LocalDateTime endTime = LocalDateTime.of(2021, 1, 3, 20, 31, 20); //比較時間 System.out.println(localDateTime.isAfter(startTime)); // 結果:true System.out.println(localDateTime.isBefore(endTime)); // 結果:false //獲取毫秒數(使用Instant) System.out.println(localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); // 結果:1637739570129 //獲取秒數(使用Instant) System.out.println(localDateTime.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond()); // 結果:1637739570 // 獲取當前時間的0點~23點 LocalDateTime beginDay = localDateTime.withHour(0).withMinute(0).withSecond(0).withNano(0); LocalDateTime endDay = localDateTime.withHour(23).withMinute(59).withSecond(59); // 獲取本月的第一天的0點0分0秒和最后一天的23點59分59秒 LocalDateTime beginMonth = localDateTime.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0); LocalDateTime endMonth = localDateTime.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59); // LocalDateTime轉Date Date date = Date.from(localDateTime.toInstant(ZoneOffset.of("+8"))); // Date轉LocalDateTime date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime(); // LocalDateTime獲取秒數 Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")); // LocalDateTime獲取毫秒數 Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
效果如下:
v源碼地址
https://github.com/toutouge/javademosecond/tree/master/hellolearn
作 者:請叫我頭頭哥
出 處:http://www.cnblogs.com/toutou/
關於作者:專注於基礎平台的項目開發。如有問題或建議,請多多賜教!
版權聲明:本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接。
特此聲明:所有評論和私信都會在第一時間回復。也歡迎園子的大大們指正錯誤,共同進步。或者直接私信我
聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角【推薦】一下。您的鼓勵是作者堅持原創和持續寫作的最大動力!