Let me first explain why you get what you get when you don't name the format. toString is called in ZonedDateTime, which in turn calls toString on on DateTime and Offset, which calls toString in LocalDate and LocalTime. These toStrings do not use formatters, so even if you can specify a default formatter, it will not be called when it implicitly converts ZonedDateTime to a string.
There are many ways to simplify the creation of this formatted string. One way is to use a utility class that you would replace in all of your log statements. I do not necessarily suggest the following, but it most closely matches what you ask for:
public class MyAwesomeUtility { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss a Z"); public static String getFormattedZonedDateTime() { return ZonedDateTime.now().format(FORMATTER); } }
The next parameter is not the same as ZonedDateTime is final, as pointed out by @assylias. Leaving it here anyway.
If you really want to accomplish what you asked in the question that overrides the now method to return an object that would give the specified format when calling toString , you would need to do something like the following (NOTE: THIS IS ANTI-PATTERN. DO NOT DO THIS ):
public class DefaultFormattedZonedDateTime extends ZonedDateTime { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss a Z"); @Overwrite public String toString() { this.format(FORMATTER); } }
Then, since now in ZonedDateTime is static and still returns ZonedDateTime, you will need to use AspectJ (you cannot use AOP in the static method only with spring) to return this new object instead.
Daniel Moses
source share