import org.springframework.format.annotation.DateTimeFormat; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date etd; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date eta;<\/code><\/pre>
This code works fine. But I found that an exception is thrown when the time is an empty string, so I add this:
I don't think that you can use both together, as only one of them will be picked by the system, but what you can do is extend standard behavior and add empty string processing. As I like the declarative way of parsing strings based on the @DateTimeFormat<\/code> annotation I will share the code which shows how easy it is to extend default functionality.
So to start with Spring uses
AnnotationFormatterFactory<\/code> s that create formatters to format and parse values of fields annotated with a particular annotation.
The
@DateTimeFormat<\/code> annotation has several
AnnotationFormatterFactory<\/code> s but one which parses and formats the
java.util.Date<\/code> s is
DateTimeFormatAnnotationFormatterFactory<\/code> , so what we need to do is just override it add our custom handling and register the formatter.
Its is pretty straightforward to do that via
WebMvcConfigurationSupport<\/code> .
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Override
protected void addFormatters(FormatterRegistry registry) {
registry.addFormatterForFieldAnnotation(new DateTimeFormatAnnotationFormatterFactory(){
@Override
public Parser<?> getParser(DateTimeFormat annotation, Class<?> fieldType) {
var defaultParser = super.getParser(annotation, fieldType);
return (Parser<Object>) (text, locale) -> {
// if the text value is empty just return null and do not try to parse
if(!StringUtils.hasText(text)){
return null;
}
return defaultParser.parse(text, locale);
};
}
});
}
}
Since Spring framework 5.3.5<\/a> , @DateTimeFormat<\/code> supports defining a list of fallback patterns for parsing the date time if it fails to parse with the primary pattern.
That means you could simply do :
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date etd;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss",fallbackPatterns = "yyyy-MM-dd")
private Date eta;
Date<\/code> class is very much outdated (pun intended).
Please switch to package
java.time<\/code> and use one of the implementations of Temporal<\/a> interface.
In your case you should look at LocalDate<\/a> and LocalDateTime<\/a> classes. Then your
@DateTimeFormat<\/code> will work correctly
"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.