Spring trucantes time part from a Date GET RequestParam

36 Views Asked by At

I have a Spring MVC REST controller with an object as param:

public List<AccessResponse> getAccesses(AccessRequestParams params) throws Exception {
    log.debug("Received get request");
}

The param is a simple bean with some properties, I copy here just the important date property:

public class AccessRequestParams  {

    Date since=null;
    ...

    public SincePageFilter() {
        super();
    }

    public Date getSince() {
        return since;
    }

    public void setSince(Date since) {
        this.since = since;
    }
    
    
}

When I call this URL:

http://localhost:8080/v1/accesses?since=2017-05-04T12:08:56

The since property is filled with 2017-05-04 00:00:00, Why it truncates the time part?

I also tried to:

  • Call this URL with space instead of "T" between date and time http://localhost:8080/v1/accesses?since=2017-05-04%2012:08:56
  • Added @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") annotation for Date since property.

But I did not find any solution.

My Spring config has this BEAN:

@Bean
public FormattingConversionService mvcConversionService() {
    DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false);

    DateTimeFormatterRegistrar dateTimeRegistrar = new DateTimeFormatterRegistrar();
    dateTimeRegistrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    dateTimeRegistrar.setDateTimeFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    dateTimeRegistrar.registerFormatters(conversionService);

    DateFormatterRegistrar dateRegistrar = new DateFormatterRegistrar();
    dateRegistrar.setFormatter(new DateFormatter("yyyy-MM-dd"));
    dateRegistrar.registerFormatters(conversionService);

    return conversionService;
}
1

There are 1 best solutions below

2
Mar-Z On BEST ANSWER

You have registered a global DateFormatter for the type java.util.Date with format yyyy-MM-dd. This works as expected.

  • You can change it to include the time part.

  • Or you can use a type LocalDateTime in your request bean. Then the other format will be valid: yyyy-MM-dd HH:mm:ss (with space).

  • Or you can remove the configuration and let Spring use the default formats.