【发布时间】:2018-08-02 07:19:37
【问题描述】:
我正在为我的项目编写 rest api 来创建、检索和修改数据库中的值。 该模型有一个 sql.Date 字段,如果我给出日期例如 2018-01-35(yyyy-MM-dd),则在执行 POST 请求时,它会自动转换为 2018-02-04。 我想避免这种情况,以便它可以告诉我给定的日期无效。
我在SO中搜索并尝试了这种方法,
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dob;
但这没有任何作用,所以我尝试了另一种方法
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
但这仅检查格式,例如如果我将值设为“1993”,它会给出错误但不检查“1993-01-35”。
我也试过了,
public static boolean dateChecker(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setLenient(false);
calendar.setTime(date);
try{
calendar.getTime();
}catch(Exception e)
{
System.out.println(e.getMessage());
return false;
}
return true;
}
但是当我调试它时,这个方法已经把“1993-01-35”变成了“1993-02-04”。
模型是,
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
private Date dob;
这是我的 POST 方法,
@RequestMapping(value = "/patient",method = RequestMethod.POST,consumes = "application/json")
public ResponseEntity<?> createPatient(@RequestBody Patient patient)
{
if(patient.getPatientId()!=null)
{
Patient patient1 = patientRepository.findOne(patient.getPatientId());
if(patient1!=null)
{
return new ResponseEntity("Patient for the given patient Id already exists.",HttpStatus.BAD_REQUEST);
}
}
System.out.println(patient.getDob());//Here I am getting 1993-02-04 when i give date as 1993-01-35
请帮我解决这个问题。
【问题讨论】:
标签: mysql json spring rest spring-boot