创建一个Formatter类
public class USLocalDateFormatter implements Formatter<LocalDate> { public static final String US_PATTERN="MM/dd/yyyy"; public static final String NORMAL_PATTERN="dd/MM/yyyy"; @Override public LocalDate parse(String s, Locale locale) throws ParseException { return LocalDate.parse(s,DateTimeFormatter.ofPattern(getPattern(locale))); } @Override public String print(LocalDate localDate, Locale locale) { return DateTimeFormatter.ofPattern(getPattern(locale)).format(localDate); } //根据地域不同,用户输入方式不同 public static String getPattern(Locale locale){ return isUnitedStates(locale)? US_PATTERN:NORMAL_PATTERN; } //判断是否在美国 private static boolean isUnitedStates(Locale locale){ return Locale.US.getCountry().equals(locale.getCountry()); } }
@Controller public class ProfileController { //注册一个bean,根据地理位置,确定不同格式,用于前端给用户提醒。 @ModelAttribute("dateFormat") public String localeFormat(Locale locale){ return USLocalDateFormatter.getPattern(locale); } @RequestMapping("/profile") public String displayProfile(){ return "profilePage"; } @RequestMapping(value = "/profile",method= RequestMethod.POST) public String saveProfile(@ModelAttribute("profileForm") ProfileForm profileForm){ System.out.println("save ok"+profileForm); return "profilePage"; } }配置:
<mvc:annotation-driven conversion-service="conversionServicess"/>
<bean id="conversionServicess" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatters"> <set> <bean class="org.fkit.date.USLocalDateFormatter"/> </set> </property> </bean>