Java DateTimeFormatter 问题

问题描述 投票:0回答:1

我有以下方法,它接受一个日期字符串并尝试将其格式化为 LocalDateTime 对象:

(语言环境为挪威语)

public static LocalDateTime parseDatoLocalDateTime2(String datoString, String pattern, String language) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern(pattern)
        .toFormatter(Locale.forLanguageTag(language));
    return LocalDateTime.parse(datoString, formatter);
}

据我所知,这些是正确使用的“格式代码”:

yyyy = 2024
yy = 24
MMMM = April
MMM = Apr
MM = 04
dd = 09
d = 9

所以,这有效:

String testdato1 = "8. 04. 2024 15:32";
parseDatoLocalDateTime2(testdato1, "d. MM. yyyy HH:mm", "no");

String testdato2 = "8. april 2024 15:32";
parseDatoLocalDateTime2(testdato2, "d. MMMM yyyy HH:mm", "no");

这怎么行不通?

String testdato3 = "8. apr 2024 15:32";
parseDatoLocalDateTime2(testdato3, "d. MMM yyyy HH:mm", "no");

失败了

java.time.format.DateTimeParseException: Text '8. apr 2024 15:32' could not be parsed at index 3

但是为什么呢?据我所知,“MMM”是月份的简称(“apr”、“jul”等)。

我什至变得“基本”,或者“白痴”,并询问ChatGTP:

Me: Can you show me how to use Java DateTimeFormatter to parse this string into a LocalDateTime object with Norwegian locale: "8. apr. 2024 15:32"

ChatGTP:

String dateString = "8. apr. 2024 15:32";
// Define the formatter pattern with Norwegian locale
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d. MMM. yyyy HH:mm", new Locale("no"));
    
// Parse the string into a LocalDateTime object
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
    
// Print the parsed LocalDateTime object
System.out.println(dateTime);

甚至这个代码对我来说也不起作用。它或多或少以同样的方式失败:

Text '8. apr. 2024 15:32' could not be parsed at index 7
java java-time
1个回答
0
投票

当你检查相反的方式时

import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.LocalDateTime;

DateTimeFormatter formatter = new DateTimeFormatterBuilder().
    parseCaseInsensitive().
    appendPattern("d. MMM. yyyy HH:mm").
    toFormatter(Locale.forLanguageTag("no"));

System.out.println(formatter.format(LocalDateTime.now()));

此代码片段的输出(例如在 jshell 中测试)在我的机器上且在我的当地时间:

8. apr.. 2024 16:29

因此

MMM
会转换为
apr.
,当您在之后添加
.
时,您会告诉解析器等待第二个点。

反过来说:

DateTimeFormatter formatterIn = new DateTimeFormatterBuilder().
    parseCaseInsensitive().
    appendPattern("d. MMM yyyy HH:mm").
    toFormatter(Locale.forLanguageTag("no"));
formatterIn.parse("8. apr. 2024 16:29")

毫无例外地工作得很好。请注意,在格式字符串中的

MMM
之后,我没有添加额外的点。

© www.soinside.com 2019 - 2024. All rights reserved.