You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 year
    • MM: 2-digit month
    • dd: 2-digit day
    • HH: 2-digit hour (24-hour format, use hh if you're dealing with 12-hour time)
    • mm: 2-digit minutes
    • ss: 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 with atZone(ZoneId.systemDefault()).
  • Convert to Instant: Finally, toInstant() converts the time-zoned date-time to an Instant, which represents a point on the UTC timeline.

Key Notes:

  • Always specify a time zone: LocalDateTime can't be directly converted to Instant because it lacks time zone context. Omitting this step will throw an error.
  • Double-check pattern case: Don't mix up MM (month) with mm (minutes), or HH (24-hour) with hh (12-hour) — this is a common source of bugs.

内容的提问来源于stack exchange,提问作者Aaron_ab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:29:08