簡體   English   中英

覆蓋 DateTimeFormatter 本地化的世紀日期樣式解析策略

[英]Overwrite DateTimeFormatter localized date style parsing strategy for century

我需要根據語言環境和格式樣式動態解析日期字符串。

例如,我有一個阿爾巴尼亞語言環境,它的模式為yy-MM-dd

我有以下代碼可以根據當前的語言環境和格式樣式解決此模式

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendLocalized(FormatStyle.SHORT, null)
                .toFormatter()
                .withLocale(Locale.forLanguageTag("sq-AL"));
TemporalAccessor temporalAccessor = formatter.parseBest("92-07-09", LocalDateTime::from, LocalDate::from, LocalTime::from);
System.out.println(temporalAccessor);

輸入字符串被解析為09/07/2092

但我需要將此日期解析為09/07/1992

添加.appendValueReduced的代碼不起作用

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendLocalized(FormatStyle.SHORT, null)
                .appendValueReduced(ChronoField.YEAR, 2, 2, LocalDate.now().minusYears(80))
                .toFormatter()
                .withLocale(Locale.forLanguageTag("sq-AL"));

我已經在 StackOverflow 上搜索了答案,但沒有找到任何沒有.appendPattern()並且基於語言環境和格式樣式的答案

提前致謝!

以此答案為基礎,您可以首先從輸入字符串中提取模式,如下所示:

String shortPattern =
    DateTimeFormatterBuilder.getLocalizedDateTimePattern(
        FormatStyle.SHORT,
        null,
        IsoChronology.INSTANCE,
        Locale.forLanguageTag("sqi-AL")
    );
System.out.println(shortPattern); //y-MM-d

現在,您可以使用具有特定年份說明的格式化程序。 由於 year 現在由appendValueReduced處理, appendValueReduced現在明確給出了模式,並刪除了y s:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendOptional(DateTimeFormatter.ofPattern(shortPattern.replaceAll("y","")))
                .appendValueReduced(ChronoField.YEAR, 2, 4, LocalDate.now().minusYears(80))
                .appendOptional(DateTimeFormatter.ofPattern(shortPattern.replaceAll("y","")))
                .toFormatter();

TemporalAccessor temporalAccessor = formatter.parseBest("92-07-09", LocalDate::from, LocalDateTime::from);
System.out.println(temporalAccessor); //1992-07-09

appendOptional的原因是,如果語言環境模式以年份結尾,則可能會導致解析錯誤。 例如,您的代碼 ( sq-AL ) 中語言環境的模式實際上是dMyy 所以我們需要在兩端檢查年份。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM