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

Spring Boot中Swagger UI显示带毫秒LocalDateTime与格式指定不符问题

解决Spring Boot中Swagger UI显示带毫秒的LocalDateTime问题

你遇到的问题核心是Swagger默认的LocalDateTime序列化逻辑未遵循Jackson配置,加上注解存在无效配置,导致示例和「Try it out」功能的时间格式不符合预期。以下是具体解决步骤:

1. 修正字段注解的无效配置

你的代码里@DateTimeFormat(pattern = )是空的,属于无效配置——如果是用于请求参数绑定,就补全匹配的格式;如果只需要控制序列化/反序列化,直接移除这个注解即可。同时给@JsonFormat加上时区参数,和你标注的UTC格式保持一致:

@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", timezone = "UTC")
@Schema(example = "2022-10-30T12:45:00", description = "UTC格式的日期时间")
private LocalDateTime dateTime;

2. 配置Jackson全局日期格式

在application.yml(或application.properties)中配置Jackson全局序列化规则,确保所有LocalDateTime类型都按指定格式输出:

spring:
  jackson:
    date-format: yyyy-MM-dd'T'HH:mm:ss
    time-zone: UTC
    serialization:
      write-dates-as-timestamps: false

3. 让Swagger适配Jackson序列化规则

若使用SpringDoc OpenAPI(当前推荐方案)

添加配置类,让Swagger复用Jackson的ObjectMapper生成示例值,避免自动生成带毫秒的格式:

@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI customOpenAPI(ObjectMapper objectMapper) throws JsonProcessingException {
        // 生成无毫秒的示例时间并去除序列化后的引号
        String dateExample = objectMapper.writeValueAsString(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS))
                .replace("\"", "");
        return new OpenAPI()
                .components(new Components()
                        .addSchemas("LocalDateTime",
                                new StringSchema()
                                        .example(dateExample)
                                        .format("date-time")));
    }
}

若使用SpringFox(旧版Swagger)

通过directModelSubstitute将LocalDateTime直接替换为String类型,强制使用指定的示例格式:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.your.package"))
                .paths(PathSelectors.any())
                .build()
                .directModelSubstitute(LocalDateTime.class, String.class)
                .apiInfo(new ApiInfoBuilder().title("API文档").build());
    }
}

4. 强制Swagger使用@Schema指定的示例

若上述配置后示例仍不生效,可关闭Swagger的自动示例生成功能,强制使用@Schema中定义的example值。以SpringDoc为例,在application.yml中添加:

springdoc:
  default-schema-example: false

完成以上配置后,Swagger UI的示例值和「Try it out」功能中的时间格式就会符合指定的yyyy-MM-dd'T'HH:mm:ss格式,不再带有毫秒。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 08:15:59