Save a formatted String to a LocalDate

2019-08-08 18:52发布

问题:

I have a DateConverter class:

public class DateConverter extends StringConverter<LocalDate> {

    String pattern = "EEE, dd. MM. uuuu";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern,Locale.US);

    @Override
    public String toString(LocalDate object) {
        try {
            return formatter.format(object);
        } catch(Exception ex) {
            return "";
        }      
    }

    @Override
    public LocalDate fromString(String string) {
        try {
            return LocalDate.parse(string, formatter);
        } catch(Exception ex) {
            return null;
        }
    }

    public String getPattern(){
        return pattern;
    }

}

And I have this piece of code:

allProd.forEach((prod) -> {
    DateConverter dc = new DateConverter();
    LocalDate onMarket = dc.fromString(dc.toString(prod.getOnMarket()));
    System.out.println("localdate:" + onMarket);
    System.out.println("string:"+dc.toString(onMarket));
}

Which prints this:

localdate:2012-11-08
string:Thu, 08. 11. 2012
localdate:2011-11-13    
string:Sun, 13. 11. 2011
localdate:2002-04-11
string:Thu, 11. 04. 2002

What I want is that my LocalDate value is formatted like the string value is. Because I have a class which has a LocalDate field and the field should always be formatted. So I don't want to change the field datatype to string.

回答1:

You cannot. A LocalDate does not have and cannot have a format in it.

If you adhere to separation of model and presentation, it would also be incorrect to put the format into the date. The LocalDate is part of your model (I presume). The EEE, dd. MM. uuuu format belongs in your presentation. Your converter class bridges the two.

A LocalDate holds a value, a date in the calendar, nothing else. Much the same way as an int holds a value. For example, an int may hold the value 64458. For presentation you may format it into strings like 000000064458, +64458 or 64,458 or even 64458.00 or in hex. The int stays the same. In the same way your LocalDate stays the same no matter which formatting operations you do. You can have your desired format only in a String outside the LocalDate.

As a compromise you may fit your class with a getFormattedDate method that formats your date into a string. You decide whether this would blur the separation between model and presentation too much, or since the date should always be formatted, in this case it’s acceptable to you.