Just like conversion service, formatter conversion service (DefaultFormattingConversionService) can also be used with DataBinder.
DefaultFormattingConversionService
package com.logicbig.example; import org.springframework.format.Formatter; import java.text.ParseException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; public class RFC1123LocalDateTimeFormatter implements Formatter<LocalDateTime> { private ZoneId targetZoneId; public RFC1123LocalDateTimeFormatter(ZoneId targetZoneId) { this.targetZoneId = targetZoneId; } @Override public LocalDateTime parse(String text, Locale locale) throws ParseException { return ZonedDateTime.parse(text, DateTimeFormatter.RFC_1123_DATE_TIME) .withZoneSameInstant(targetZoneId) .toLocalDateTime(); } @Override public String print(LocalDateTime object, Locale locale) { return object.format(DateTimeFormatter.RFC_1123_DATE_TIME); } }
package com.logicbig.example; import java.time.LocalDateTime; public class MyObject { private LocalDateTime dateAtTargetTimeZone; public LocalDateTime getDateAtTargetTimeZone() { return dateAtTargetTimeZone; } public void setDateAtTargetTimeZone(LocalDateTime dateAtTargetTimeZone) { this.dateAtTargetTimeZone = dateAtTargetTimeZone; } @Override public String toString() { return "MyObject{" + "dateAtTargetTimeZone=" + dateAtTargetTimeZone + '}'; } }
package com.logicbig.example; import org.springframework.beans.MutablePropertyValues; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.validation.DataBinder; import java.time.ZoneId; public class ConversionServiceWithDataBinderExample { public static void main(String[] args) { MutablePropertyValues mpv = new MutablePropertyValues(); mpv.add("dateAtTargetTimeZone", "Thu, 25 Aug 2016 08:59:00 GMT"); DataBinder dataBinder = new DataBinder(new MyObject()); DefaultFormattingConversionService service = new DefaultFormattingConversionService(); service.addFormatter(new RFC1123LocalDateTimeFormatter(ZoneId.of("America/Chicago"))); dataBinder.setConversionService(service); dataBinder.bind(mpv); dataBinder.getBindingResult() .getModel() .entrySet() .forEach(System.out::println); } }
target=MyObject{dateAtTargetTimeZone=2016-08-25T03:59}org.springframework.validation.BindingResult.target=org.springframework.validation.BeanPropertyBindingResult: 0 errors
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.