1. 概述
本文学习如何将 Java 中的 String 解析为 Timestamp 对象,以及如何将 Timestamp 格式化为字符串。
2. String 转 Timestamp
2.1. 标准时间格式
如何需要解析的时间字符串是JDBC timestamp格式 - yyyy-m[m]-d[d] hh:mm:ss[.f…]
,那很简单。使用 Timestamp.valueOf
:
Timestamp.valueOf("2018-11-12 01:02:03.123456789")
时间模式说明
Pattern | 描述 | 示例 |
---|---|---|
yyyy | Represents the year, and it’s mandatory to have four digits for it. | 2018 |
m[m] | For the month component, we must have either one or two digits (from 1 to 12). | 1, 11 |
d[d] | For the day of month value, we must have either one or two digits (from 1 to 31). | 7, 12 |
hh | Stands for the hour of the day, with allowed values from 0 to 23. | 01, 16 |
mm | Stands for minutes of the hour, with allowed values from 0 to 59. | 02, 45 |
ss | Stands for seconds in the minute, with allowed values from 0 to 59. | 03, 52 |
[.f…] | Represents optional fractions of a second, can be up to nanoseconds precision so the allowed values are from 0 to 999999999. | 12, 1567, 123456789 |
2.2. 其他时间格式
如果是非 JDBC timestamp 格式的字符串,valueOf 还支持接受 LocalDateTime 类型的参数。
所以我们可以将其转换为LocalDateTime类型,这样我们就支持任意类型的格式了
String pattern = "MMM dd, yyyy HH:mm:ss.SSSSSSSS";
String timestampAsString = "Nov 12, 2018 13:02:56.12345678";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime localDateTime = LocalDateTime.from(formatter.parse(timestampAsString));
然后调用 Timestamp.valueOf()
Timestamp timestamp = Timestamp.valueOf(localDateTime);
assertEquals("2018-11-12 13:02:56.12345678", timestamp.toString());
3. Timestamp 转 String
同样,默认格式输出的是 JDBC timestamp类型
assertEquals("2018-11-12 13:02:56.12345678", timestamp.toString());
通过中间类转换为 ISO-8601 标准格式:
Timestamp timestamp = Timestamp.valueOf("2018-12-12 01:02:03.123456789");
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
String timestampAsString = formatter.format(timestamp.toLocalDateTime());
assertEquals("2018-12-12T01:02:03.123456789", timestampAsString);
4. 总结
本文中的示例源码可在GitHub上获取。