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

Java/Scala中如何将时间戳字符串转为yyyy-MM-dd HH:mm:ss格式?

解决LocalDateTime输出格式不符问题
  • 问题根源:你调用LocalDateTime.parse()得到的是LocalDateTime对象,直接打印时会触发它的默认toString()方法,输出固定格式yyyy-MM-dd'T'HH:mm(秒为0时自动省略),和你定义的DateTimeFormatter无关;datetime_format.parse()返回的是TemporalAccessor对象,打印时同样用默认格式展示。

  • 解决方案:要输出指定的yyyy-MM-dd HH:mm:ss格式,必须调用DateTimeFormatter.format()方法,把解析后的日期时间对象传入进行格式化。

修正后的代码示例:

import java.time._
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime

val datasettime = "2024-03-18 00:00:00"
val datetime_format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

// 步骤1:将字符串解析为LocalDateTime对象
val localDateTime = LocalDateTime.parse(datasettime, datetime_format)
// 步骤2:用自定义格式化器输出指定格式的字符串
println(datetime_format.format(localDateTime)) // 输出:2024-03-18 00:00:00

// 也可以直接链式调用简化代码
println(datetime_format.format(LocalDateTime.parse(datasettime, datetime_format)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 13:22:38