Skip to content

Commit 3799799

Browse files
committed
fix: precision of InstantPatternLegacyFormatter
To get the correct precision in the `InstantPatternLegacyFormatter` we need to replace the legacy `n` pattern letter with its `DateTimeFormatter` equivalent `S`.
1 parent 9657563 commit 3799799

File tree

2 files changed

+5
-1
lines changed

2 files changed

+5
-1
lines changed

log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NamedInstantPatternTest.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,6 @@ void compatibilityOfLegacyPattern(NamedInstantPattern namedPattern) {
4141
MutableInstant instant = new MutableInstant();
4242
instant.initFromEpochSecond(javaTimeInstant.getEpochSecond(), javaTimeInstant.getNano());
4343
assertThat(legacyFormatter.format(instant)).isEqualTo(formatter.format(instant));
44+
assertThat(legacyFormatter.getPrecision()).isEqualTo(formatter.getPrecision());
4445
}
4546
}

log4j-core/src/main/java/org/apache/logging/log4j/core/util/internal/instant/InstantPatternLegacyFormatter.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,10 @@ final class InstantPatternLegacyFormatter implements InstantPatternFormatter {
4646
private final BiConsumer<StringBuilder, Instant> formatter;
4747

4848
InstantPatternLegacyFormatter(final String pattern, final Locale locale, final TimeZone timeZone) {
49-
this.precision = new InstantPatternDynamicFormatter(pattern, locale, timeZone).getPrecision();
49+
// Replaces 'n' used in legacy patterns with 'S' to obtain the right precision.
50+
// In legacy patterns, the precision of 'n' depends on the pattern length, but
51+
// in `DateTimeFormatter`, it is always nanoseconds.
52+
this.precision = new InstantPatternDynamicFormatter(pattern.replace('n', 'S'), locale, timeZone).getPrecision();
5053
this.pattern = pattern;
5154
this.locale = locale;
5255
this.timeZone = timeZone;

0 commit comments

Comments
 (0)