Scala中14位时间戳字符串转Instant对象的正确方法
How to convert a 14-digit "YYYYMMDDhhmmss" string to an Instant in Java/Kotlin
The reason Instant.parse(t1) fails is straightforward: Instant expects input in the ISO-8601 standard format (like 2001-05-31T02:12:54Z), but your string uses a custom, delimiter-free format. To fix this, you need to define a custom DateTimeFormatter to parse the 14-digit string, then convert it to an Instant by explicitly specifying a time zone.
Here's the working Kotlin code tailored to your example:
import java.time.Instant import java.time.LocalDateTime import java.time.ZoneOffset import java.time.format.DateTimeFormatter fun main() { val t1 = "20010531021254" // Create a formatter that matches your 14-digit timestamp pattern val timeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss") // Parse the string to LocalDateTime, attach UTC offset, then convert to Instant val targetInstant = LocalDateTime.parse(t1, timeFormatter) .atOffset(ZoneOffset.UTC) .toInstant() println(targetInstant) // Output: 2001-05-31T02:12:54Z }
Breakdown of the steps:
- Custom Formatter:
DateTimeFormatter.ofPattern("yyyyMMddHHmmss")is built to exactly match your input format:yyyy: 4-digit yearMM: 2-digit monthdd: 2-digit dayHH: 2-digit hour (24-hour format, usehhif you're dealing with 12-hour time)mm: 2-digit minutesss: 2-digit seconds
- Parse to LocalDateTime: This gives us a date-time object without time zone information (since your input string doesn't include one).
- Attach Time Zone: We use
atOffset(ZoneOffset.UTC)to tie the local time to UTC (matching your expected result). If your timestamp corresponds to your system's default time zone instead, replace this withatZone(ZoneId.systemDefault()). - Convert to Instant: Finally,
toInstant()converts the time-zoned date-time to anInstant, which represents a point on the UTC timeline.
Key Notes:
- Always specify a time zone:
LocalDateTimecan't be directly converted toInstantbecause it lacks time zone context. Omitting this step will throw an error. - Double-check pattern case: Don't mix up
MM(month) withmm(minutes), orHH(24-hour) withhh(12-hour) — this is a common source of bugs.
内容的提问来源于stack exchange,提问作者Aaron_ab
相关产品推荐
相关产品推荐

