79802824

Date: 2025-10-28 12:59:18
Score: 0.5
Natty:
Report link

Yes, you can register a custom Converter that handles both Unix timestamps (milliseconds) and formatted date strings. Spring Boot will automatically apply it to @RequestParam, @PathVariable, and @RequestBody bindings.



import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class FlexibleDateConverter implements Converter<String, Date> {

    private static final String[] DATE_FORMATS = {
        "yyyy-MM-dd HH:mm:ss",
        "yyyy-MM-dd'T'HH:mm:ss",
        "yyyy-MM-dd",
        "MM/dd/yyyy"
    };

    @Override
    public Date convert(String source) {
        
        try {
            long timestamp = Long.parseLong(source);
            return new Date(timestamp);
        } catch (NumberFormatException e) {
          
        }

        
        for (String format : DATE_FORMATS) {
            try {
                return new SimpleDateFormat(format).parse(source);
            } catch (Exception e) {    
            }
        }

        throw new IllegalArgumentException("Unable to parse date: " + source);
    }
}
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @RequestParam
  • User mentioned (0): @PathVariable
  • User mentioned (0): @RequestBody
  • Low reputation (1):
Posted by: Siripireddy Giri