我使用Spring Framework作为服务API,使用org.joda.time.DateTime
进行日期时间解析。具体来说,我使用的是ISOFormatter.dateOptionalTimeParser()
,它允许用户灵活地使用日期,或同时使用日期和时间。
相信我,我已经看到所有这些相关的问题,我已经可以告诉人们会指出我,例如this和this等
以前,我将日期作为String
,然后使用上面提到的服务层中的joda格式化程序处理它,但现在我想在控制器中添加请求验证,这意味着如果请求是在语法上不正确,请求甚至不应该转到服务层。
我尝试使用@DateTimeFormat(iso = ISO.DATE_TIME)
的多种变体,以及在格式化的情况下指定pattern
字符串,但没有任何运气。
@RequestMapping(value = URIConstants.TEST_URL, method = RequestMethod.GET)
public @ResponseBody String getData(@RequestParam(required = false) DateTime from,
@RequestParam(required = false) DateTime to) {
return dataService.fetchDataFromDB(from, to);
}
我应该怎么做才能确保我从用户那里得到的日期符合ISO 8601 dateOptionalTime
格式?我可以应用多种模式来实现这个吗?
答案 0 :(得分:4)
你也可以创建一个转换器来处理它。我在下面的示例中使用了OffsetDateTime,但可以使用LocalDateTime轻松替换。有关详细文章,请参阅此网址 - http://www.baeldung.com/spring-mvc-custom-data-binder
即使我在这个问题上挣扎了一段时间,但它还没有奏效。诀窍是使用@Component
注释并为我做。
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class OffsetDateTimeConverter implements Converter<String, OffsetDateTime> {
@Override
public OffsetDateTime convert(final String source) {
if (source == null || source.isEmpty()) {
return null;
}
return OffsetDateTime.parse(source, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
}
答案 1 :(得分:2)
我最终为此创建了一个POJO,我使用String
从ISODateTimeFormat.dateOptionalTimeParser()
解析时间:
public class DateOptionalTime {
private DateTime date;
private DateTimeFormatter formatter = ISODateTimeFormat.dateOptionalTimeParser();
public DateOptionalTime() {
}
public DateOptionalTime(String date) {
if (date != null) {
this.setDate(formatter.parseDateTime(date));
}
}
public DateTime getDate() {
return date;
}
public void setDate(DateTime date) {
this.date = date;
}
public LocalDateTime getLocalDateTime() {
return date.toLocalDateTime();
}
}
在控制器中,我这样使用它:
@RequestMapping(value = URIConstants.TEST_URL, method = RequestMethod.GET)
public @ResponseBody String getData(@RequestParam(required = false) DateOptionalTime from,
@RequestParam(required = false) DateOptionalTime to) {
return dataService.fetchDataFromDB(from, to);
}
根据ISO标准验证日期格式,如果格式不正确,则返回BAD_REQUEST状态。