Java中的DateTimeFormatter函数如何格式化日期和时间?
Java中的DateTimeFormatter类是用来格式化日期和时间的类。它可以将日期和时间转换为指定的格式,并且可以从字符串中解析日期和时间。
Java中的DateTimeFormatter类使用ISO-8601标准作为日期和时间的默认格式。但是,它也可以使用用户定义的格式进行格式化操作。DateTimeFormatter类提供了三种格式化方法:format(),formatTo()和format(java.time.temporal.TemporalAccessor)。
1.format()方法
format()方法接受一个TemporalAccessor对象,并返回一个格式化后的字符串。这个方法有很多不同的重载形式,可以使用不同的格式化字符串和LocalDate、LocalDateTime、ZonedDateTime、OffsetTime等对象进行格式化。
以下是一些常见的格式化示例:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.now();
String formattedDate = dtf.format(date);
System.out.println(formattedDate);
输出结果:2022-05-03
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.now();
String formattedDateTime = dtf.format(dateTime);
System.out.println(formattedDateTime);
输出结果:2022-05-03 18:45:22
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
ZonedDateTime zonedDateTime = ZonedDateTime.now();
String formattedTime = dtf.format(zonedDateTime);
System.out.println(formattedTime);
输出结果:18:45:22
2.formatTo()方法
formatTo()方法与format()方法类似,它也接受一个TemporalAccessor对象,但是它将格式化后的字符串追加到一个Appendable对象中。这个方法只能由DateTimeFormatterBuilder类的appendXXX()方法来使用。
以下是一些常见的示例:
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR)
.appendLiteral("-")
.appendValue(ChronoField.MONTH_OF_YEAR)
.appendLiteral("-")
.appendValue(ChronoField.DAY_OF_MONTH)
.toFormatter();
LocalDate date = LocalDate.now();
StringBuffer sb = new StringBuffer();
dtf.formatTo(date, sb);
System.out.println(sb.toString());
输出结果:2022-05-03
3.format(TemporalAccessor)方法
format(TemporalAccessor)方法接受一个TemporalAccessor对象,并根据DateTimeFormatter实例的格式化字符串将其格式化为字符串。这个方法与format()方法类似,但不返回结果。
以下是一些常见的示例:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.now();
dtf.format(dateTime);
System.out.println(dtf.format(dateTime));
输出结果:2022-05-03 18:45:22
现在我们可以使用DateTimeFormatter类来格式化日期和时间了。要注意的是,有许多不同的格式化字符串可以使用,可以根据需要进行自定义。FormatStyle枚举提供了几个预定义的格式化字符串类型,可以使用这些类型来格式化日期和时间。DateTimeFormatter类还提供了parse()方法可以从给定的字符串中解析日期和时间。这个类是Java 8中新增的,因此如果您使用较早的版本,将无法使用此类。
