1、DateTimeFoematter 提供了三种格式化的方法
2、代码查验学习
package com.test;
import org.junit.Test;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;
public class TestDateTimeFormatter {
@Test
public void test(){
//方式一:预定义的标准格式
DateTimeFormatter iso1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime now1 = LocalDateTime.now();
System.out.println("时间为:"+now1);
//格式化
String str1 = iso1.format(now1);
//System.out.println(iso1);
System.out.println("日期>>>到>>>字符串:"+str1);
//方式二:本地化相关格式
TemporalAccessor parse1 = iso1.parse("2022-01-24T14:08:44.978");
System.out.println("字符串>>>到>>>日期:"+parse1);
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
String str2 = dateTimeFormatter1.format(now1);
System.out.println("本地格式化为ofLocalizedDate的SHORT为:"+str2);
//方式三:自定义格式
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
String str3 = dateTimeFormatter.format(LocalDateTime.now());
System.out.println("自定义的格式:"+str3);
}
}
运行结果
时间为:2022-01-24T14:42:38.512
日期>>>到>>>字符串:2022-01-24T14:42:38.512
字符串>>>到>>>日期:{},ISO resolved to 2022-01-24T14:08:44.978
本地格式化为ofLocalizedDate的SHORT为:22-1-24
自定义的格式:2022-01-24 02:42:38