Java.time.DateTimeFormat Unexpected behavior

In Java 8, the java.time package using LocalDatewith DateTimeFormatter.ISO_WEEK_DATE:

LocalDate date = LocalDate.of(2015, 12, 28);
date.format(DateTimeFormatter.ISO_WEEK_DATE).equals("2015-W53-1");

as expected but

date.format(DateTimeFormatter.ofPattern("YYYY'-W'ww'-'e")).equals("2016-W01-2");

This is a full week! What for? Which spell would make my custom template work just like an inline template?

+4
source share
2 answers

Java 8 uses Builder

Here is the implementation for DateTimeFormatter.ISO_WEEK_DATE. The source uses Builder ( DateTimeFormatterBuilder) and not the encoded string.

From this OpenJDK source code for Java 8 , which seems to be the current development version after updating Java 8 Update 72 (I don't own the OpenJDK Site).

public static final DateTimeFormatter ISO_WEEK_DATE;
    static {
        ISO_WEEK_DATE = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendValue(IsoFields.WEEK_BASED_YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
                .appendLiteral("-W")
                .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2)
                .appendLiteral('-')
                .appendValue(DAY_OF_WEEK, 1)
                .optionalStart()
                .appendOffsetId()
                .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
    }

First day of the week

, , . ISO , . , .appendValue(DAY_OF_WEEK, 1) , , , IsoChronology .

Locale

, , Locale. , , 2015-W53-1, : 2016-W01-2.

LocalDate localDate = LocalDate.of ( 2015 , 12 , 28 );
String builtIn = localDate.format ( DateTimeFormatter.ISO_WEEK_DATE ); // 2015-W53-1

DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "YYYY'-W'ww'-'e" );

formatter = formatter.withLocale ( Locale.GERMANY );  // 2015-W53-1
String custom = localDate.format ( formatter );
System.out.println ( "formatter.locale: " + formatter.getLocale () + " | localDate: " + localDate + " | builtIn: " + builtIn + " | custom: " + custom );

formatter = formatter.withLocale ( Locale.US );  // 2016-W01-2
custom = localDate.format ( formatter );
System.out.println ( "formatter.locale: " + formatter.getLocale () + " | localDate: " + localDate + " | builtIn: " + builtIn + " | custom: " + custom );

formatter.locale: de_DE | localDate: 2015-12-28 | builtIn: 2015-W53-1 | custom: 2015-W53-1

formatter.locale: ru_RU | localDate: 2015-12-28 | builtIn: 2015-W53-1 | custom: 2016-W01-2

+2

: ` w` joda java.time

, Locale, .

+1

Source: https://habr.com/ru/post/1626821/


All Articles