0

Is there any way to make Spring decodes both string (es. yyyy-mm-dd HH:MM:ss) and long (unixtime milliseconds) for Date objects?

1
  • For what? Request parameters? Json bodies? XML? So depending on what you want the solution will differ. Commented Oct 29 at 10:31

1 Answer 1

1

You can register a custom Converter that tries both Unix timestamps and formatted strings. Simple example:

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

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

    @Override
    public Date convert(String source) {
            return new Date(Long.parseLong(source));

        for (String f : FORMATS) {
            return new SimpleDateFormat(f).parse(source);
        }
    }
}

Spring Boot will automatically pick this up for @RequestParam, @PathVariable, and @RequestBody bindings.

For LocalDateTime, just implement Converter<String, LocalDateTime> and use DateTimeFormatter / Instant.ofEpochMilli(). If you decide to use this snippet, make sure to use some try catches is my recommendation.

Sign up to request clarification or add additional context in comments.

2 Comments

This will not work with @RequestBody as that doesn't use a converter but Jackson (by default unless a different library is added and used). It will only work for request parameters, path variables and if you are luckily for header values.
Ok thanks, how can I let it work with requestbody?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.