大摇大摆的日期字段与日期时间字段

我正在使用 swagger 来测试我的 rest api,我的实体类的属性之一是一个日期字段,我需要 yyyy-mm-dd 格式的日期,但是 swagger 模型架构将此字段显示为日期-时间而不是日期字段,因此它给出了带有时间和区域的日期.如何将此日期时间转换为日期字段?

I am using swagger to test my rest api, one of the property of my entity class is a date field for which I need the date in yyyy-mm-dd format , but swagger model schema is showing this field as date-time instead of date field, therefore it gives date with time and zone. How can I convert this date-time into date field ?

我有一个java实体类TimeEntry.java,它的属性之一是Date,看起来像这样.

I have a java entity class TimeEntry.java one of its property is Date, it looks like this.

@ApiModelProperty(required = true)
@JsonFormat(pattern = DATE_FORMAT)
private Date date;

对于这个字段,在 swagger UI 模型架构上,字段日期显示为 "date": "2016-01-08T22:34:22.337Z" 但我需要它作为 "date":"2016-01-08" .

for this field, on the swagger UI model schema, the field date displays as "date": "2016-01-08T22:34:22.337Z" but I need this as "date":"2016-01-08" .

我尝试了以下方法:

1.

@ApiModelProperty(required = true, dataType="date")  
@JsonFormat(pattern = DATE_FORMAT)   
private Date date;

2.尝试遵循此代码(覆盖 OverrideConvertor 类),但找不到 swagger-core 1.3 版 mvn 存储库.仅提供 1.5 版本 https://github.com/swagger-api/swagger-core/wiki/overriding-models

2.Tried to follow along this code (override OverrideConvertor class) but could not find swagger-core 1.3 version mvn repo. Only available is 1.5 version https://github.com/swagger-api/swagger-core/wiki/overriding-models

  1. 显然,他们从 1.5 版本中删除了 OverrideConvertor 类https://groups.google.com/forum/#!topic/swagger-swaggersocket/ChiknyHZiP4

请帮忙.

推荐答案

java.util.Date 的问题(实际上是问题之一)是它真的是一个日期时间,而且招摇正确地检测到它.我确实理解 @JsonFormat 也是一种解决方法——swagger 在类型检测期间不支持该注释.

The problem (one of the problems actually) with java.util.Date is that it's really a date-time, and swagger correctly detects it as such. I do understand that the @JsonFormat is a workaround for this as well--swagger does not support that annotation during it's type detection.

您有三个选项来正确处理日期类型.

You have three options to properly handle date types.

1) 使用 Joda 的 LocalDate 作为数据类型.如果您声明了 private LocalDate date,它将正确显示.

1) Use Joda's LocalDate as the datatype. If you declared private LocalDate date, it would appear correctly.

2) 使用java8的LocalDate,同上.

2) Use java8's LocalDate, same as above.

3) 告诉 swagger 在检测注解中的类型时使用上述任何一种,但保持属性为 java.util.Date 类型:

3) Tell swagger to use either of the above when detecting the type in the annotation, but keep the property as type java.util.Date:

@ApiModelProperty(required = true, dataType = "org.joda.time.LocalDate")

然后,扫描时,swagger 会将其检测为 date 格式的字符串.

Then, when scanning, swagger will detect this as a date formatted string.

相关文章