我想用阿拉伯-印度教數字決議字串日期時間和時區,所以我寫了一個這樣的代碼:
String dateTime = "????-??-??T??:??:?? ??:??";
char zeroDigit = '?';
Locale locale = Locale.forLanguageTag("ar");
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX")
.withLocale(locale)
.withDecimalStyle(DecimalStyle.of(locale).withZeroDigit(zeroDigit));
ZonedDateTime parsedDateTime = ZonedDateTime.parse(dateTime, pattern);
assert parsedDateTime != null;
但我收到了例外:
java.time.format.DateTimeParseException:無法在索引 19 處決議文本“????-??-??T??:??:?? ??:??”
我查了很多關于 Stackoverflow 的問題,但我還是不明白我做錯了什么。
dateTime = "????-??-??T??:??:?? 02:00"當時區不使用阿拉伯-印度數字時,它可以正常作業。
uj5u.com熱心網友回復:
你的dateTime字串是錯誤的,被誤解了。它顯然試圖符合 ISO 8601 格式并失敗了。因為 ISO 8601 格式使用 US-ASCII 數字。
如果只有 ISO 8601 的數字是正確的, java.time ( Instant,OffsetDateTime和ZonedDateTime) 類將在沒有任何格式化程式的情況下決議您的字串。在絕大多數情況下,我會采用您的方法:嘗試按原樣決議字串。在這種情況下不是。對我來說,在決議之前更正字串更有意義。
String dateTime = "????-??-??T??:??:?? ??:??";
char[] dateTimeChars = dateTime.toCharArray();
for (int index = 0; index < dateTimeChars.length; index ) {
if (Character.isDigit(dateTimeChars[index])) {
int digitValue = Character.getNumericValue(dateTimeChars[index]);
dateTimeChars[index] = Character.forDigit(digitValue, 10);
}
}
OffsetDateTime odt = OffsetDateTime.parse(CharBuffer.wrap(dateTimeChars));
System.out.println(odt);
輸出:
2021-11-08T02:21:08 02:00
編輯:當然,如果您可以教育字串的發布者使用 US-ASCII 數字,那就更好了。
編輯:我知道我鏈接到下面的維基百科文章說:
表示必須用阿拉伯數字和特定計算機字符(如“-”、“:”、“T”、“W”、“Z”)的組合來書寫,這些字符在標準中被賦予了特定的含義;…
這是造成混亂的一個可以想到的原因。鏈接到的文章阿拉伯數字說:
阿拉伯數字是十位數字:0、1、2、3、4、5、6、7、8、9。
編輯:感謝@HolgerCharBuffer在這種情況下引起我的注意。ACharBuffer實作了CharSequence,parsejava.time的方法需要的型別,這樣我們就不必將char陣列轉換回String.
鏈接
- 維基百科文章:ISO 8601
- 維基百科文章:阿拉伯數字
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352785.html
