How to format LocalDate object to MM/dd/yyyy and have format persist

后端 未结 5 1183
自闭症患者
自闭症患者 2020-11-27 07:37

I am reading text and storing the dates as LocalDate variables.

Is there any way for me to preserve the formatting from DateTimeFormatter so that when I call the Lo

5条回答
  •  一整个雨季
    2020-11-27 07:59

    No, you cannot have a format persist, because you cannot override toString of LocalDate (constructor of LocalDate is private, it is imposible extends) and there are not a method to change the format in LocalDate persistently.

    Maybe, you could create a new class and use an static method to change the format, but you have always to use MyLocalDate.myToString(localDate) instead localDate.toString() when you want other format.

     public class MyLocalDate {
        
        public static String myToString(LocalDate localDate){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
            return localDate.format(formatter);
        }   
    }
    

    When you invoke you have to use this way

    FechaInicioTextField.setText(MyLocalDate.myToString(fechaFacturaInicial));
    

    instead of

    FechaInicioTextField.setText(fechaFacturaInicial.toString());
    

提交回复
热议问题