Close

Spring Framework - @DateTimeFormat Examples

Spring Framework 

This example shows how to use @DatTimeFormat and @NumberFormat annotations in a Spring core application.

package com.logicbig.example;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.datetime.DateTimeFormatAnnotationFormatterFactory;
import org.springframework.format.number.NumberFormatAnnotationFormatterFactory;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;

import java.util.Date;
import java.util.Map;

public class SpringFormatAnnotationExample {

public static void main (String[] args) {

DefaultFormattingConversionService conversionService =
new DefaultFormattingConversionService(false);

conversionService.addFormatterForFieldAnnotation(
new NumberFormatAnnotationFormatterFactory());

conversionService.addFormatterForFieldAnnotation(
new DateTimeFormatAnnotationFormatterFactory());

Order order = new Order();
DataBinder dataBinder = new DataBinder(order);
dataBinder.setConversionService(conversionService);


MutablePropertyValues mpv = new MutablePropertyValues();
mpv.add("price", "2.7%");
mpv.add("date", "2016");

dataBinder.bind(mpv);

Object target = dataBinder.getTarget();
System.out.println(target);

BindingResult bindingResult = dataBinder.getBindingResult();
System.out.println(bindingResult);
}

}

Output

Order{price=0.027, date=Fri Jan 01 00:00:00 CST 2016}
org.springframework.validation.BeanPropertyBindingResult: 0 errors

package com.logicbig.example;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;

import java.util.Date;

public class Order {
@NumberFormat(style = NumberFormat.Style.PERCENT)
private Double price;

@DateTimeFormat(pattern = "yyyy")
private Date date;
.............
}
Original Post




See Also