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

Spring中使用LocalDateTime获取当前时间并按指定格式转换的问题

LocalDateTime 格式化指定格式的解决方案

错误原因

  • 逻辑颠倒:你需要的是将已有的LocalDateTime对象格式化为指定格式的字符串,而非将LocalDateTime默认输出的ISO格式字符串,用自定义格式反向解析,两种格式规则完全不匹配,所以会触发索引位置的解析异常。
  • 格式串书写错误:你定义的模式为MM//dd//yyyy,多写了斜杠,需求里要求的是单斜杠分隔的MM/dd/yyyy。
  • 认知偏差:LocalDateTime是时间对象,本身不携带任何展示格式,只有转换为字符串的时候才需要指定格式规则,你最后将解析结果赋值回LocalDateTime变量的操作没有实际意义。

正确实现代码

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

// 工具方法示例
public String getFormattedCurrentTime() {
    // 获取当前时间对象
    LocalDateTime now = LocalDateTime.now();
    // 定义格式化规则,指定Locale.US是为了输出AM/PM英文标识,不指定则默认使用系统区域的标识
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy h:mm a", Locale.US);
    // 直接调用format方法完成格式化
    return now.format(formatter);
}

输出示例:08/23/2021 6:24 PM

补充说明

如果后续需要把该自定义格式的字符串转回LocalDateTime对象,才需要用到parse方法,示例如下:

String formattedStr = "08/23/2021 6:24 PM";
LocalDateTime parsedTime = LocalDateTime.parse(formattedStr, formatter);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:12:00