Home > Back-end >  When does Spring parse String to LocalDate?
When does Spring parse String to LocalDate?

Time:01-08

I've have a Spring Boot application, and I have a service that takes LocalDate as an input.

e.g. ../resource/list?date=2022-01-01

This works fine with the DateTimeFormat annotation to use iso standard. However, I wanted to pass a string value as "today". For example, ../resource/list?date=today. If the value is today, then I want to convert that to today's date and send the request to the database. Since the type of the parameter is LocalDate, normally I'm getting HTTP 400 bad request.

My question is, when does Spring parse String to LocalDate? If I can know that stage, I can check the value before Spring and apply my business logic.

CodePudding user response:

and I have a service that takes LocalDate as an input.

If by "service" you mean a Spring Boot application with and endpoint mapping for the given URL, I would instead register a converter to convert the String value to a LocalDate:

public class CustomStringToLocalDateConverter implements Converter<String, LocalDate> {

    @Override
    public LocalDate convert(String from) {
        return "today".equalsIgnoreCase(from) ? LocalDate.now() : LocalDate.parse(from);
    }
}

and to register the converter:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new CustomStringToLocalDateConverter());
    }
}
  •  Tags:  
  • Related