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

24小时转12小时制代码异常:12:01:00转换结果错误

问题排查与修复方案

我来帮你搞定这个时间转换的问题,核心问题出在时间格式符的误用上,具体分析和修复如下:

问题根源

你当前的代码里,sourceFormat定义为"hh:mm:ss"——这里的hh是12小时制的小时格式符(对应1-12的数值),但你的输入是24小时制的时间字符串(比如12:01:00)。当用hh去解析24小时制的12点时,Java的SimpleDateFormat会把它识别为午夜12点(12 AM),这就导致后续格式化输出的结果不符合预期。

正确的24小时制小时格式符应该是HH(对应0-23的数值),用它来解析24小时制的时间才是正确的。

修复后的代码

只需要修改sourceFormat的格式符,同时完善一下异常处理避免空指针问题:

private static final String sourceFormat = "HH:mm:ss"; // 改用24小时制的HH
private static final String targetFormat = "hh:mm a";

public static String convertTimeFormat(String dateStr) {
    if (dateStr == null || dateStr.trim().isEmpty()) {
        return "";
    }
    Log.d("date", dateStr + "---" + sourceFormat + "---" + targetFormat);
    SimpleDateFormat form = new SimpleDateFormat(sourceFormat);
    Date date = null;
    try {
        date = form.parse(dateStr);
    } catch (ParseException e) { // 建议用具体的ParseException而非笼统的Exception
        e.printStackTrace();
        return ""; // 解析失败时返回空字符串,避免后续format空指针
    }
    SimpleDateFormat postFormater = new SimpleDateFormat(targetFormat);
    String newDateStr = postFormater.format(date);
    Log.d("Lead Response", newDateStr);
    return newDateStr;
}

补充说明

这里再明确两个关键格式符的区别,避免以后再踩坑:

  • HH:代表24小时制的小时,取值范围是00-23,用于解析或格式化24小时制的时间
  • hh:代表12小时制的小时,取值范围是01-12,需要配合a(AM/PM标识)一起使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:37:32