我正在尝试创建一个约会。我试图将 Date 传递到 Postman 查询中,我尝试制作一个转换器,但出现此错误:
这是我的实体类代码:
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Appointment extends BaseEntity {
@NotNull
@Temporal(TemporalType.TIME)
@DateTimeFormat(style = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ")
private Date startDate;
@NotNull
@Temporal(TemporalType.TIME)
@DateTimeFormat(style = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
private Date endDate;
正如你所看到的,我尝试进行转换,但不知道为什么它不起作用。这是我的图书馆:
我的预约DTO类(class):
@Data
@NoArgsConstructor
@AllArgsConstructor
public abstract class AppointmentDTO extends BaseDTO {
@JsonProperty("start_date")
private Date startDate;
@JsonProperty("end_date")
private Date endDate;
@JsonProperty("user_id")
private User user;
private Set<Activity> activities;
}
最佳答案
添加此配置:
@Configuration
public class DateTimeFormatConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(registry);
}
}
在我的 Controller 中,它收到 ISO 格式的日期:
因此,reistrar.setUseIsoFormat(true)
确保 Spring 将日期解析为 ISO。这意味着您必须确保日期采用正确的 ISO 格式。将日期传递给存储库方法时,您不需要执行任何特殊操作,只需将其保留为字符串即可。
此外,在您的实体中,我建议您使用 LocalDateTime
或 LocalDate
而不是 Date
。
@Column(name = "student_date_of_birth")
private LocalDate studentDateOfBirth; // 2020-05-20
关于java - 将日期传递给 postman 时出现“未找到转换器”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61901678/