Java日期相关_DateTimeFormatter

package com.pyk.teat;

import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.LocalDateTime;

public class Test05 {
	public static void main(String[] args) {
		//格式化类:DateTimeFormatter
		
		//方式一:预定义的标准格式:如ISO_LOCAL_TIME;ISO_LOCAL_DATE;ISO_LOCAL_DATE_TIME
		DateTimeFormatter df1=DateTimeFormatter.ISO_LOCAL_DATE_TIME;
		//df1就可以帮我们完成LocalDateTime与String之间的互相转换
		//LocalDateTime-->String
		//创建LocalDateTime实例
		LocalDateTime now=LocalDateTime.now();
		String str=df1.format(now);
		System.out.println(str);
		
		//String-->LocalDateTime
		TemporalAccessor parse=df1.parse("2022-05-01T18:34:46.5974595");
		
		
		//方式二:本地化相关的格式。如ofLocalDateTime()
		//参数:FormatStyle.LONG/FormatStyle.MEDIUM/FormatStyle.SHORT
		//FormatStyle.LONG:2022年5月1日 下午06时52分12秒
		//FormatStyle.MEDIUM:2022-5-1 18:52:12
		//FormatStyle.SHORT:22-5-1 下午6:53
		DateTimeFormatter df2=DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
		//LocalDateTime-->String
		//创建LocalDateTime实例
		LocalDateTime now1=LocalDateTime.now();
		String str2=df2.format(now1);
		System.out.println(str2);
		
		//String-->LocalDateTime
		TemporalAccessor parse1=df2.parse("22-5-1 下午6:55");
		System.out.println(parse1);
		
		//方式三:自定义的格式。如:ofPattern("yyyy-MM-dd hh:mm:ss")重点
		DateTimeFormatter df3=DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
		//LocalDateTime-->String
		//创建LocalDateTime实例
		LocalDateTime now2=LocalDateTime.now();
		String format=df3.format(now2);
		System.out.println(format);
		
		//String-->LocalDateTime
		TemporalAccessor parse2=df3.parse("2022-05-01 06:22:01");
		System.out.println(parse2);
	}
}


版权声明:本文为SAITWATERLaKE原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。