代码之家  ›  专栏  ›  技术社区  ›  kakemonsteret

Java DateTimeFormatter问题

  •  0
  • kakemonsteret  · 技术社区  · 4 周前

    我有以下方法,它获取一个日期字符串,并尝试将其格式化为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
    
    1 回复  |  直到 4 周前
        1
  •  1
  •   cyberbrain    4 周前

    当你像这样检查opsite时

    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 在格式字符串中,我没有添加额外的点。