LocalDateTime与DateTimeFormatter,毫秒值,时间和文本转换
生活随笔
收集整理的這篇文章主要介紹了
LocalDateTime与DateTimeFormatter,毫秒值,时间和文本转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*=== 毫秒值與時間互相轉換 ===*//** 毫秒值>>時間* 思路:先轉換成Instant,再加上時區(ZoneOffset也可以)轉換成LocalDateTime* 思路:使用LocalDateTime.ofEpochSecond 傳入秒,和納秒值*/long milli = 1555666999123L;//首先來一個long毫秒值,也可使用System.currentTimeMillis()LocalDateTime time1 = LocalDateTime.ofInstant(Instant.ofEpochMilli(milli), ZoneId.systemDefault());LocalDateTime time2 = LocalDateTime.ofEpochSecond(milli / 1000, (int)(milli % 1000 * 1000_000), ZoneOffset.ofHours(8));System.out.println("毫秒值轉換時間方式一:" + time1);//2019-04-19T17:43:19.123System.out.println("毫秒值轉換時間方式二:" + time2);//2019-04-19T17:43:19.123System.out.println("兩種方式結果是否一致:" + time1.equals(time2));//true/** 時間>>毫秒值* 思路:先根據當前時間的時區轉換成Instant,再使用Instant對象的toEpochMilli方法* 思路:使用toEpochSecond(ZoneOffset)和getNano()分別獲得秒(整數部分,不足一秒的舍棄)和納秒,再統一單位到毫秒進行相加*/LocalDateTime time = LocalDateTime.of(2019, 4, 19, 17, 43, 19, 123 * 1000_000);//首先有一個時間對象,2019-04-19T17:43:19.123long milli1 = time.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();long milli2 = time.toEpochSecond(ZoneOffset.ofHours(8)) * 1000 + time.getNano() / 1000_000;System.out.println("時間轉換毫秒值方式一:" + milli1);System.out.println("時間轉換毫秒值方式二:" + milli2);/*=== 文本與時間互相轉換 ===*///文本與時間轉換需要一個模板和一個 DateTimeFormatterString pattern = "自定義文本''yyyy-MM-dd HH:mm:ss.SSS''";DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(pattern);//java8版本在pattern帶毫秒的解析中異常問題可使用DateTimeFormatterBuilder的appendPattern和appendValue方式進行構建(未驗證)/*DateTimeFormatter timeFormatter = new DateTimeFormatterBuilder().appendPattern("自定義文本''yyyy-MM-dd HH:mm:ss.").appendValue(ChronoField.MILLI_OF_SECOND).appendPattern("''").toFormatter();*//** 文本>>時間* 思路:直接使用LocalDateTime.parse方法,傳入文本和一個DateTimeFormatter實例* 思路:使用DateTimeFormatter對象的parse方法解析出一個TemporalAccessor對象,再最為LocalDateTime.from的參數*/String text = "自定義文本'2019-04-19 17:43:19.123'";//假設有這樣一個文本,需要轉換為時間LocalDateTime localDateTime1 = LocalDateTime.parse(text, timeFormatter);LocalDateTime localDateTime2 = LocalDateTime.from(timeFormatter.parse(text));System.out.println(localDateTime1);//2019-04-19T17:43:19.123System.out.println(localDateTime2);//2019-04-19T17:43:19.123System.out.println(localDateTime1.equals(localDateTime2));//true/** 時間>>文本* 思路:DateTimeFormatter和LocalDateTime都可以作為主調,另一個則最為參數*/LocalDateTime localDateTime = LocalDateTime.of(2019, 4, 19, 17, 43, 19, 123 * 1000_000);//假設有這樣一個時間對象,2019-04-19T17:43:19.123 需要轉換為文本System.out.println("時間轉換為自定義文本:" + timeFormatter.format(localDateTime));System.out.println("時間轉換為自定義文本:" + localDateTime.format(timeFormatter));/*=== 文本轉換為毫秒值 ===*//** 文本=>時間=>毫秒值* 參考以上*/
總結
以上是生活随笔為你收集整理的LocalDateTime与DateTimeFormatter,毫秒值,时间和文本转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 季羡林基金会与孔明在线联手弘扬国学文化
- 下一篇: 数据库并发抢红包_微信高并发抢红包秒杀实