datetimeformatter用法
时间: 2023-04-22 10:02:45 浏览: 240
`DateTimeFormatter` 是 Java 8 中的一个类,用于格式化和解析日期和时间。它提供了丰富的格式选项,以灵活处理各种日期和时间字符串格式。例如,您可以使用它将日期转换为字符串,或者将字符串转换为日期。使用方法如下:
```
// 创建 DateTimeFormatter 对象,指定格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 格式化 LocalDateTime 对象
LocalDateTime now = LocalDateTime.now();
String str = formatter.format(now);
System.out.println(str); // 输出:2022-01-01 12:34:56
// 解析字符串为 LocalDateTime 对象
LocalDateTime dateTime = LocalDateTime.parse("2022-01-01 12:34:56", formatter);
System.out.println(dateTime); // 输出:2022-01-01T12:34:56
```
详情请参考:
- https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/time/format/DateTimeFormatter.html
相关问题
DateTimeFormatter使用方法
DateTimeFormatter是Java 8中的一个日期时间格式化类,用于将日期时间对象转换为字符串或将字符串转换为日期时间对象。使用方法如下:
1. 创建DateTimeFormatter对象:
a. 通过ofPattern方法传入格式化字符串创建DateTimeFormatter对象,例如:DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
b. 通过ofLocalizedDateTime方法传入FormatStyle和Locale创建DateTimeFormatter对象,例如:DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(Locale.CHINA);
2. 将日期时间对象转换为字符串:
a. 调用format方法,传入日期时间对象,返回字符串,例如:String str = formatter.format(LocalDateTime.now());
3. 将字符串转换为日期时间对象:
a. 调用parse方法,传入字符串和DateTimeFormatter对象,返回日期时间对象,例如:LocalDateTime dateTime = LocalDateTime.parse("2022-01-01 00:00:00", formatter);
DateTimeFormatter使用
DateTimeFormatter是Java 8中的一个日期时间格式化类,用于格式化或解析日期、时间,类似于SimpleDateFormat。使用DateTimeFormatter可以将日期时间对象转换为指定格式的字符串,也可以将字符串解析为日期时间对象。
以下是DateTimeFormatter的使用方法:
1. 格式化:日期时间对象 -> 字符串
```java
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
String str1 = formatter.format(now);
System.out.println(now); // 输出:2021-07-22T14:23:45.678
System.out.println(str1); // 输出:2021-07-22 14:23:45
```
在这个例子中,我们创建了一个DateTimeFormatter对象,指定了日期时间的格式为"yyyy-MM-dd HH:mm:ss",然后使用format()方法将当前时间对象now格式化为字符串str1。
2. 解析:字符串 -> 日期时间对象
```java
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
TemporalAccessor parse = formatter.parse("2021-07-22 14:23:45");
LocalDateTime dateTime = LocalDateTime.from(parse);
System.out.println(dateTime); // 输出:2021-07-22T14:23:45
```
在这个例子中,我们同样创建了一个DateTimeFormatter对象,指定了日期时间的格式为"yyyy-MM-dd HH:mm:ss",然后使用parse()方法将字符串"2021-07-22 14:23:45"解析为TemporalAccessor对象parse,最后使用from()方法将TemporalAccessor对象转换为LocalDateTime对象dateTime。
阅读全文
相关推荐















