有时,以下代码会导致 Android 应用程序崩溃:
try {
(new Date()).toString());
} catch (Exception ex) {
...
}
堆栈跟踪:
java.lang.AssertionError:
at android.icu.impl.TimeZoneNamesImpl$ZNames.getNameTypeIndex (TimeZoneNamesImpl.java:724)
at android.icu.impl.TimeZoneNamesImpl$ZNames.getName (TimeZoneNamesImpl.java:790)
at android.icu.impl.TimeZoneNamesImpl.getTimeZoneDisplayName (TimeZoneNamesImpl.java:183)
at android.icu.text.TimeZoneNames.getDisplayName (TimeZoneNames.java:261)
at java.util.TimeZone.getDisplayName (TimeZone.java:405)
at java.util.Date.toString (Date.java:1066)
显然,无法捕获错误。有没有办法防止这种情况?
最佳答案
如果您在使用 new Date() 时遇到 AssertionError,这看起来很奇怪并且可能与 Android 8 问题相关,而不是您的代码,您可以使用 java.time 来自 Java 8 而不是像这样的 java.util.Date:
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy/MM/dd HH:mm:ss")
.withZone(ZoneId.systemDefault()); //you must add time zone because of Instant
Instant currentTimestamp = Instant.now();
System.out.print(formatter.format(currentTimestamp));
关于java - 如何防止 java.util.Date.toString 崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51845112/