Java中阿拉伯语和常规日期的日期解析问题

rob*_*bin 5 java date

我有一个日期转换器功能,如:

public static LocalDate getLocalDateFromString(String dateString) {
    DecimalStyle defaultDecimalStyle = DateTimeFormatter.ISO_LOCAL_DATE.getDecimalStyle();
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE.withDecimalStyle(defaultDecimalStyle.withZeroDigit('\u0660'));
    LocalDate date = LocalDate.parse(dateString, dateTimeFormatter);
    return date;
}
Run Code Online (Sandbox Code Playgroud)

它适用于阿拉伯日期,例如????-??-??,但是当我传递正常日期时2019-07-31,则抛出异常,因为格式器的类型不同:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-07-31' could not be parsed at index 0
Run Code Online (Sandbox Code Playgroud)

我无法控制传递的日期,因为它是由用户传递的。

如何使用相同的函数解析两个日期?

Ole*_*.V. 4

了解你的字符串

\n\n

DateTimeFormatter\xe2\x80\x99t 不会让你变得很容易。我推测这个选择背后可能有一个目的:如果您可以让自己预先知道要解析的字符串中使用哪种数字,那么它\xe2\x80\x99 会更好。您可以想一想:您能否说服字符串的来源将此信息传递给您?

\n\n

尝尝并采取相应行动

\n\n

如果没有,当然有办法。以下内容是低级的,但应该是通用的。

\n\n
public static LocalDate getLocalDateFromString(String dateString) {\n    DateTimeFormatter dateFormatter = DateTimeFormatter.ISO_LOCAL_DATE;\n    // Take a digit from dateString to determine which digits are used\n    char sampleDigit = dateString.charAt(0);\n    if (Character.isDigit(sampleDigit)) {\n        // Subtract the numeric value of the digit to find the zero digit in the same digit block\n        char zeroDigit = (char) (sampleDigit - Character.getNumericValue(sampleDigit));\n        assert Character.isDigit(zeroDigit) : zeroDigit;\n        assert Character.getNumericValue(zeroDigit) == 0 : zeroDigit;\n        DecimalStyle defaultDecimalStyle = dateFormatter.getDecimalStyle();\n        dateFormatter = dateFormatter\n                .withDecimalStyle(defaultDecimalStyle.withZeroDigit(zeroDigit));\n    }\n    // If the examined char wasn\xe2\x80\x99t a digit, the following parsing will fail;\n    // but in that case the best we can give the caller is the exception from that failed parsing.\n    LocalDate date = LocalDate.parse(dateString, dateFormatter);\n    return date;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

让\xe2\x80\x99s 尝试一下:

\n\n
    System.out.println("Parsing Arabic date string to  "\n            + getLocalDateFromString("\xd9\xa2\xd9\xa0\xd9\xa1\xd9\xa9-\xd9\xa0\xd9\xa4-\xd9\xa1\xd9\xa5"));\n    System.out.println("Parsing Western date string to "\n            + getLocalDateFromString("2019-07-31"));\n
Run Code Online (Sandbox Code Playgroud)\n\n

该片段的输出是:

\n\n
\n
Parsing Arabic date string to  2019-04-15\nParsing Western date string to 2019-07-31\n
Run Code Online (Sandbox Code Playgroud)\n
\n