代码如下:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;
public class StartApplication {
public static void main(String[] args) {
//方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISo_LOCAL_TIME
DateTimeFormatter isoLocalDateTime = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//格式化-->日期-->字符串
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
String str = isoLocalDateTime.format(localDateTime);
System.out.println(str);
//解析:字符串-->日期
TemporalAccessor parse = isoLocalDateTime.parse("2022-05-10T16:18:03.676");
System.out.println(parse);
//方式二:
//本地化相关的格式。如:ofLocalizedDateTime()
// FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
//格式化
String format = dateTimeFormatter.format(localDateTime);
System.out.println(format);
//本地化相关的格式。如:ofLocalizedDate()
//FormatStyle.FULL / FormatStyle.LONG /FormatStyle.MEDIUM / FormatStyle.SHORT:适用于LocalDate
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
//格式化
String format1 = dateTimeFormatter1.format(LocalDateTime.now());
System.out.println(format1);
//方式三:自定义的格式。如: ofPattern("yyyy-MM-dd hh:mm:ss E")
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
//格式化
String format2 = dateTimeFormatter2.format(LocalDateTime.now());
System.out.println(format2);
//解析
TemporalAccessor parse1 = dateTimeFormatter2.parse("2022-05-10 04:38:19");
System.out.println(parse1);
}
}
结果如下:
2022-05-10T16:40:08.432
2022-05-10T16:40:08.432
{},ISO resolved to 2022-05-10T16:18:03.676
2022年5月10日 下午04时40分08秒
2022年5月10日 星期二
2022-05-10 04:40:08
{HourOfAmPm=4, NanoOfSecond=0, MinuteOfHour=38, MilliOfSecond=0, SecondOfMinute=19, MicroOfSecond=0},ISO resolved to 2022-05-10
这篇博客详细介绍了Java 8中LocalDateTime的使用,包括预定义格式、本地化格式和自定义格式的日期时间格式化和解析,展示了如何将日期时间转换为字符串以及反向解析字符串到日期时间。
1858

被折叠的 条评论
为什么被折叠?



