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

Kotlin中使用Calendar加2小时后如何输出完整yyyy-MM-dd HH:mm:ss格式时间

问题原因

你缺少了将运算完成后的时间对象重新格式化为目标格式字符串的步骤,目前仅完成了时间加法运算,输出时直接读取了时间部分,因此仅显示时分秒。

修复方案

方案1:沿用现有Calendar + SimpleDateFormat实现

补充格式化输出步骤即可:

val simpleDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
val cal = Calendar.getInstance()
cal.time = simpleDate.parse(regdate)
cal.add(Calendar.HOUR, 2)
// 新增格式化步骤,将修改后的时间转为目标格式字符串
val targetTime = simpleDate.format(cal.time)

此时输出targetTime即可得到2021-12-02 13:30:05。

方案2:更推荐的java.time实现(Java 8+/Android API 26+可用)

SimpleDateFormat存在线程不安全问题,更推荐使用官方推出的java.time系列API实现:

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

val regdate = "2021-12-02 11:30:05"
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
val originTime = LocalDateTime.parse(regdate, formatter)
val targetTime = originTime.plusHours(2).format(formatter)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:24:06