且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不正确地将字符串转换为日期?

更新时间:2023-02-06 14:15:53

建议:尽可能使用

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.

如何解决?好吧,要么缩短输入时间字符串并失去一些精度,要么使用首选的

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))