在Spring Boot 中,你可以通过自定义 @DateTimeFormat
来接受多种日期格式。为此,你需要做以下几个步骤:
DateFormatter
类:此类将定义如何解析和格式化日期。ConversionService
或 FormatterRegistry
:将自定义的 DateFormatter
注册到 Spring 的 ConversionService
中。@InitBinder
方法来绑定你自定义的 DateFormatter
。以下是一个详细的示例:
DateFormatter
类首先,创建一个新的类来定义自定义的 DateFormatter
。
import org.springframework.format.Formatter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class CustomDateFormatter implements Formatter<Date> {
private static final String[] DATE_FORMATS = new String[] {
"yyyy-MM-dd",
"MM/dd/yyyy",
"dd-MM-yyyy"
};
@Override
public Date parse(String text, Locale locale) throws ParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format).parse(text);
} catch (ParseException ignored) {
}
}
throw new ParseException("Unparseable date: " + text, -1);
}
@Override
public String print(Date object, Locale locale) {
return new SimpleDateFormat(DATE_FORMATS[0]).format(object);
}
}
ConversionService
或 FormatterRegistry
在你的 Spring 配置类(通常是继承 WebMvcConfigurer
)中注册这个自定义的 DateFormatter
。
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new CustomDateFormatter());
}
}
你可以通过 @InitBinder
方法来绑定你自定义的 DateFormatter
。
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.addCustomFormatter(new CustomDateFormatter());
}
// Your endpoints here
}
这样配置后,你的 Spring Boot 应用将能够接受多种日期格式。你可以在控制器方法中使用 @DateTimeFormat
注解来指定日期字段。例如:
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Date;
@RestController
public class MyController {
@GetMapping("/date")
public String getDate(@RequestParam @DateTimeFormat Date date) {
return "Parsed date: " + date;
}
}
在这个示例中,@RequestParam
注解会根据你自定义的 DateFormatter
自动解析传入的日期参数。