LocalDateTime - pit

In with the new Date API, when we have encountered a lot of wood pit, here to tell you how to solve the string conversion LocalDateTimemethods

9028759-fb1af6772e01d915.jpg
java

Instructions

conventional

String valueIn = "2018-01-24 10:13:52";
DateTimeFormatter DATETIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime ldt = LocalDateTime.parse(valueIn, DATETIME);
System.out.println(ldt);

Output

2018-01-24T10:13:52

dream

But I want a result like this fishes

2018-01-24T10:13:52

Transfer date
then we can write

DateTimeFormatter DATETIME = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

If the number it back with milliseconds? We can write

DateTimeFormatter DATETIME = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");

SpringBoot unified treatment

The following configuration is in the context of scanning range SpringBoot

@ControllerAdvice
public class VControllerAdvice extends ValidateControllerAdvice{
  private static final DateTimeFormatter LOCAL_DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  private static final DateTimeFormatter LOCAL_DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                this.setValue(LocalDate.parse(text, LOCAL_DATE));
            }
        });
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                this.setValue(LocalDateTime.parse(text, LOCAL_DATE_TIME));
            }
        });
    }
}

PS: Perfect


9028759-07315bb8dadcd082.png

Guess you like

Origin blog.csdn.net/weixin_34072857/article/details/90840102