1. 程式人生 > 其它 >JDK8中出現的新的日期API---java.time.format.DateTimeFormatter 類

JDK8中出現的新的日期API---java.time.format.DateTimeFormatter 類

技術標籤:JAVA字串java

java.time.format.DateTimeFormatter 類的作用是 格式化 解析 日期或時間,用於替代前面介紹的jdk8之前的類— java.text.SimpleDateFormat日期自定義格式轉換類

三種例項化方式:常用第三種方式

常用方法:

前兩種例項化方法:(知道就行,用得少)


        //      方式一:預定義的標準格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期-->字串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);
        System.out.println(str1);//2019-02-18T15:42:18.797

        //解析:字串 -->日期
        TemporalAccessor parse = formatter.parse("2019-02-18T15:42:18.797");
        System.out.println(parse);

//        方式二:
//        本地化相關的格式。如:ofLocalizedDateTime()
//        FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :適用於LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        //格式化
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//2019年2月18日 下午03時47分16秒


//      本地化相關的格式。如:ofLocalizedDate()
//      FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 適用於LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
        //格式化
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);//2019-2-18

第三種例項化方法(重點):自定義的格式

//       重點: 方式三:自定義的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)

        // 指定格式來例項化一個物件
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

        //格式化:日期-->字串
        LocalDateTime localDateTime1 = LocalDateTime.now();
        System.out.println(localDateTime1);// 2020-12-15T21:03:43.182(原先的日期格式)

        String str4 = formatter3.format(localDateTime1);
        System.out.println(str4);//2020-12-15 08:52:19(格式化後的日期)

        //解析 :字串 -->日期
        //注意被解析的字串格式要與formatter3物件的格式一樣
        TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09");
        System.out.println(accessor);
        //{MinuteOfHour=52, HourOfAmPm=3, MilliOfSecond=0, MicroOfSecond=0, SecondOfMinute=9, NanoOfSecond=0},ISO resolved to 2019-02-18