0%

7.8.2 使用DateTimeFormatter解析字符串

7.8.2 使用DateTimeFormatter解析字符串

为了使用DateTimeFormatter将指定格式的字符串解析成日期、时间对象(LocalDateLocalDate,TimeLocalTime等实例),可通过日期、时间对象提供的parse(CharSequence text, DateTimeFormatter formatter)方法进行解析。

程序示例

如下程序示范了使用DateTimeFormatter解析日期、时间字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.time.*;
import java.time.format.*;

public class NewFormatterParse {
public static void main(String[] args) {
// 定义一个任意格式的日期时间字符串
String str1 = "2014==04==12 01时06分09秒";
// 根据需要解析的日期、时间字符串定义解析所用的格式器
DateTimeFormatter fomatter1 = DateTimeFormatter.ofPattern("yyyy==MM==dd HH时mm分ss秒");
// LocalDateTime类的parse解析得到日期时间对象
LocalDateTime dt1 = LocalDateTime.parse(str1, fomatter1);
System.out.println(dt1); // 输出 2014-04-12T01:06:09

// ---下面代码再次解析另一个字符串---
String str2 = "2014$$$4月$$$13 20小时";
DateTimeFormatter fomatter2 = DateTimeFormatter.ofPattern("yyy$$$MMM$$$dd HH小时");
LocalDateTime dt2 = LocalDateTime.parse(str2, fomatter2);
System.out.println(dt2); // 输出 2014-04-13T20:00

}
}
1
2
2014-04-12T01:06:09
2014-04-13T20:00

上面程序中定义了两个不同格式的日期、时间字符串,为了解析它们,程序分别使用对应的格式字符串创建了DateTimeFormatter对象,这样DateTimeFormatter即可按该格式字符串将日期、时间字符串解析成LocalDateTime对象。
编译、运行该程序,即可看到两个日期、时间字符串都被成功地解析成LocalDateTime

原文链接: 7.8.2 使用DateTimeFormatter解析字符串