DateTimeFormatter 的操作與使用 -- 通俗易懂


在上一章我們講解了LocalDate、LocalTime、LocalDateTime、Instant的操作與使用,下面講解它們之間是如何進行格式化

DateTimeFormatter這個類它只提供了時間格式化的類型,就是按你指定的格式,或者按jdk默認的格式,需要進行調用的則是時間類本身來進行調用才能進行格式化

LocalDate、LocalTime 的api是有2個方法,分別是:parse()、format()方法,時間類型的轉換可以調用這2個來進行日期時間類型的轉換

E parse(CharSequence text)

E parse(CharSequence text, DateTimeFormatter formatter)

String format(DateTimeFormatter formatter)

1.字符串轉換成日期時間類型

private static void testStringT0LocalDate() {
        // String --> LocalDate
        LocalDate localDate = LocalDate.parse("2019-12-07");

      DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
      System.out.println(LocalDate.parse("2019-10-09").format(pattern));

// String --> LocalTime
        LocalTime localTime = LocalTime.parse("07:43:53");

        // String -->LocalDateTime
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        LocalDate localDate = LocalDate.parse("2019-12-07 07:43:53",formatter);
        
        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDate);
}

2.日期時間類型轉換成字符串

private static void testLocalDateToString() {
        //localDate --> String 
        LocalDate localDate = LocalDate.now();
        String format1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);    //yyyyMMdd
        String format2 = localDate.format(DateTimeFormatter.ISO_DATE);            //yyyy-MM-dd
        
        
        //2.LocalTime  --> String
        LocalTime localTime = LocalTime.now();
        String format3 = localTime.format(DateTimeFormatter.ISO_TIME);            //20:19:22.42
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
        String format4 = localTime.format(formatter);
        
        //3.LocalDateTime  --> String        
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        String format5 = localDateTime.format(formatter2);
        
        System.out.println(format1);
        System.out.println(format2);
        System.out.println(format3);
        System.out.println(format4);
        System.out.println(format5);
        
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM