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

戏子无情 提交于 2019-12-01 17:14:55

EDIT: Considering your edit, just set parsedDate equal to your formatted text string, like so:

parsedDate = text;

A LocalDate object can only ever be printed in ISO8601 format (yyyy-MM-dd). In order to print the object in some other format, you need to format it and save the LocalDate as a string like you've demonstrated in your own example

DateTimeFormatter formatters = DateTimeFormatter.ofPattern("d/MM/uuuu");
String text = date.format(formatters);

Just format the date while printing it out:

public static void main(String[] args) {
    LocalDate date = LocalDate.now();
    DateTimeFormatter formatters = DateTimeFormatter.ofPattern("d/MM/uuuu");
    String text = date.format(formatters);
    LocalDate parsedDate = LocalDate.parse(text, formatters);

    System.out.println("date: " + date);
    System.out.println("Text format " + text);
    System.out.println("parsedDate: " + parsedDate.format(formatters));
}

Short answer: no.

Long answer: A LocalDate is an object representing a year, month and day, and those are the three fields it will contain. It does not have a format, because different locales will have different formats, and it will make it more difficult to perform the operations that one would want to perform on a LocalDate (such as adding or subtracting days or adding times).

The String representation (produced by toString()) is the international standard on how to print dates. If you want a different format, you should use a DateTimeFormatter of your choosing.

This could be possible if you could extend LocalDate and override the toString() method but the LocalDate class is immutable and therefore (secure oop) final. This means that if you wish to use this class the only toString() method you will be able to use is the above (copied from LocalDate sources):

@Override
public String toString() {
    int yearValue = year;
    int monthValue = month;
    int dayValue = day;
    int absYear = Math.abs(yearValue);
    StringBuilder buf = new StringBuilder(10);
    if (absYear < 1000) {
        if (yearValue < 0) {
            buf.append(yearValue - 10000).deleteCharAt(1);
        } else {
            buf.append(yearValue + 10000).deleteCharAt(0);
        }
    } else {
        if (yearValue > 9999) {
            buf.append('+');
        }
        buf.append(yearValue);
    }
    return buf.append(monthValue < 10 ? "-0" : "-")
        .append(monthValue)
        .append(dayValue < 10 ? "-0" : "-")
        .append(dayValue)
        .toString();
}

If you must override this behavior, you could box LocalDate and use your custom toString method but this could cause more problems than it solves!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!