我是 Java 新手。我在 json 中获取以下格式的日期和时间,
{
"appointmentDate":"2017-05-30",
"appointmentTime":"23:30:00"
}
在请求中,我正在这样做,
@NotNull(message = "appointmentDate is required")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date appointmentDate;
@NotNull(message = "appointmentTime is required")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm:ss")
private String appointmentTime;
在上面的请求类中,我使用 Date
类来获取日期并将时间视为字符串。
然后在服务类中,我尝试将字符串对象转换为日期对象,然后在表中搜索以查找表中的约会列表。
// convert into string
String dateString = null;
SimpleDateFormat sdfr = new SimpleDateFormat("yyyy-MM-dd");
dateString = sdfr.format( appointmentDate );
String dt = dateString + " " + appointmenTime;
Date startDateAndTime = null;
try {
//startDateAndTime = yyyyMMddFormat.parse(yyyyMMddFormat.format(dt));
startDateAndTime = new SimpleDateFormat(Constants.DATEANDTIME).parse(dt);
} catch (ParseException e) {
throw new IllegalArgumentException("Illegal date format");
}
但我面临的问题是,即使我输入了错误的日期,它也会给我输出。日期中的错误不会引发解析异常。
{
"appointmentDate":"20171-05-30",
"appointmentTime":"231:30:00"
}
这是我的常量
public static final String DATEANDTIME = "yyyy-MM-dd HH:mm:ss";
这是我的存储库查询,
@Query(value = "select COUNT(a.doctorId) from Appointment a WHERE a.doctorId = :doctorId AND a.scheduleFromTime = :appointmentDateTime")
Long findAppointmentExists(@Param("doctorId") Long doctorId,
@Param("appointmentDateTime") Date appointmentDateTime);
最佳答案
请允许我建议您使用现代类 LocalDate
和 LocalTime
来表示日期和时间。那么就很简单了,例如
if (appointmentDate.isAfter(LocalDate.now().plusYears(5)) {
throw new IllegalArgumentException("Too far into the future");
}
这将捕获年份值中的 5 位数年份和许多其他错误。请自行设定适当的限制。您也可以类似地禁止过去的日期,也许有更严格的限制。目前这将是内置的,因为 LocalTime
只接受 23:59:59.999999999 以内的时间。
将两者合并为一个对象
LocalDateTime startDateAndTime = LocalDateTime.of(appointmentDate, appointmentTime);
我已经凭空输入了代码片段,可能有一两个拼写错误。如果无法修复,请恢复。
我最近没有使用 Spring Boot 的经验。在这个问题中,有更多关于使用现代 Java 日期和时间类与 Spring Boot 和 Jackson 的信息:JSON Java 8 LocalDateTime format in Spring Boot 。毫无疑问,在其他地方更是如此。
关于java - 如何在Spring Boot中拒绝请求中的3位数字时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511936/