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

Kotlin/Java中SimpleDateFormat解析日期失败问题求助

解析带CEST时区的日期字符串问题解决方案

别担心,这个问题真的挺容易踩坑的,我来帮你解决~你遇到的问题主要是SimpleDateFormat对非美式时区缩写的支持不够友好,加上你用了Locale.US,导致它没法正确识别CEST(中欧夏令时)这个时区标识。

方案一:修复旧的SimpleDateFormat写法

你需要把Locale切换成欧洲地区的(比如德国Locale),同时可以显式指定对应的时区,这样就能正确解析CEST了:

private fun dateFromStringUsingPattern(dateString : String, formatPattern : String) : Date? {
    val simpleDateFormat = SimpleDateFormat(formatPattern, Locale.GERMANY)
    // 显式指定时区,避免歧义
    simpleDateFormat.timeZone = TimeZone.getTimeZone("Europe/Berlin")
    try {
        return simpleDateFormat.parse(dateString)
    } catch (e: ParseException) {
        e.printStackTrace()
        return null
    }
}

方案二:推荐使用Java 8+的新日期API(更可靠)

SimpleDateFormat本身是线程不安全的,而且在时区解析、日期处理上有很多局限性,更推荐用Java 8引入的ZonedDateTime和DateTimeFormatter,它们的表现更稳定:

import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.ZoneId
import java.util.Locale

private fun dateFromStringUsingPattern(dateString: String, formatPattern: String): ZonedDateTime? {
    val formatter = DateTimeFormatter.ofPattern(formatPattern, Locale.GERMANY)
        .withZone(ZoneId.of("Europe/Berlin"))
    return try {
        ZonedDateTime.parse(dateString, formatter)
    } catch (e: Exception) {
        e.printStackTrace()
        return null
    }
}

额外说明

  • CEST是夏令时的缩写,不同地区可能有同名的时区缩写,用完整的时区ID(比如Europe/Berlin、Europe/Paris)比缩写更准确,能避免解析歧义。
  • 如果你不需要时区信息,只是想把日期转成本地时间,也可以先解析成LocalDateTime再处理,但保留时区信息会更严谨。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:01:51