问题描述
在我的Kotlin代码中:
In my Kotlin code:
const val TS_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"
val ts = responseJsonObject.get("TS").getAsString()
val tsDate = SimpleDateFormat(TS_DATE_PATTERN).parse(ts)
val tsDateAsString = SimpleDateFormat(TS_DATE_PATTERN).format(tsDate)
logger.info("ts = " + ts + " -> tsDate = " + tsDate + " -> tsDateAsString = " + tsDateAsString)
这是(为便于阅读而格式化)结果:
And here the (formatted for readability) result:
ts = 2019-01-14T22:56:30.429582
tsDate = Mon Jan 14 23:03:39 EET 2019
tsDateAsString = 2019-01-14T23:03:39.582
您可以看到 ts 和 tsDateAsString 的时间不同,尽管它们来自同一起点.
As you can see the ts and tsDateAsString have different times, although they came from the same starting point.
例如ts = 22:56:30
,但在tsDateAsString = 23:03:39
为什么?
推荐答案
建议:尽可能使用 java.time
-实用程序.
As a suggestion: whenever you can, use java.time
-utilities.
SimpleDateFormat
具有毫秒级的特殊处理. S
解析的所有内容均以毫秒为单位.只要处理3位数毫秒,一切都很好(您甚至可以使用一个S
(即.S
)毫秒来解析它们),但是如果您使用6位数毫秒作为输入,您还将获得一个6位数的毫秒值(!).
SimpleDateFormat
has a special handling for the milliseconds. Everything that is parsed by the S
is treated as milliseconds. As long as you deal with 3-digit-milliseconds, everything is fine (you may even just use a single S
(i.e. .S
) for the milliseconds to parse them), but if you use 6-digit-milliseconds as input then you also get a 6-digit-millisecond(!)-value.
那么6位数毫秒实际上是3位数秒+ 3位数毫秒.那就是偏差的来源.
The 6-digit-milliseconds then are actually 3-digit seconds + the 3-digit milliseconds. That is where the deviation is coming from.
如何解决?好吧,要么缩短输入时间字符串并失去一些精度,要么使用首选的 DateTimeFormatter
而是使用与您的输入匹配的模式,即yyyy-MM-dd'T'HH:mm:ss.SSSSSS
:
How to solve that? Well either shorten the input time string and lose some precision or use the preferred DateTimeFormatter
instead with a pattern matching your input, i.e. yyyy-MM-dd'T'HH:mm:ss.SSSSSS
:
val TS_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
val formatter = DateTimeFormatter.ofPattern(TS_DATE_PATTERN)
val tsDate = formatter.parse(ts) // now the value as you would expect it...
将其转换为TimeStamp
将按以下方式工作:
Transforming that to a TimeStamp
will work as follows:
Timestamp.valueOf(LocalDateTime.from(tsDate))
这篇关于为什么不正确地将字符串转换为日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!