Java8提供了DateTimeFormatter来格式化输出日期时间对象
1.日期时间格式化为字符串
JDK8提供了DateTimeFormatter
对象用于格式化输出日期时间对象,只需调用DateTimeFormatter.format(dateTimeFormatter)
即可
// 获取当前日期时间
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime now = LocalDateTime.now();
System.out.println("当前时间:" + now.format(dateTimeFormatter));
执行结果
在以上代码中DateTimeFormatter.ISO_LOCAL_DATE_TIME
是JDK8中DateTimeFormatter
提供的一个默认日期时间格式化对象。使用这个默认的DateTimeFormatter对当前日期时间进行格式化,输出的日期和时间用T分隔,而且还包含毫秒值,显然不符合我们的需求,因此我们可以自定义格式化对象。
// 获取当前日期时间
LocalDateTime now = LocalDateTime.now();
// 根据指定格式生成 DateTimeFormatter 对象
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:ss:mm");
System.out.println("当前时间:" + now.format(dateTimeFormatter2));
执行结果
在上面的代码中,使用DateTimeFormatter
类的静态方法ofPattern
生成了指定格式yyyy-MM-dd HH:ss:mm
的格式化对象dateTimeFormatter2
,然后将其传入now.format
方法参数中;即可得到我们定制格式的日期时间字符串。
2.将字符串解析为日期时间对象
// 根据指定格式生成 DateTimeFormatter 对象
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:ss:mm");
LocalDateTime localDateTime = LocalDateTime.parse("2008-08-08 20:00:00", dateTimeFormatter);
System.out.println(localDateTime);
执行结果
如上,将日期时间字符串和传入LocalDateTime.parse()
方法即可得到该字符串标识的日期时间对象