java - 如何防止 java.util.Date.toString 崩溃?
问题描述
有时,以下代码会导致 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 8中的java.time而不是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));
推荐阅读
- vue.js - 如何创建基于 Vuetify 的浏览器扩展?
- typescript - 我在哪里可以找到 TypeScript 接口来定义 OpenAPI Json?
- css - SCSS 语法定义 @include font(400,16pt);
- assembly - MASM - 过程和宏之间的差异
- azure - 如何在 Azure 上扩展 Kubernetes?
- linq - Linq 查询导致异常的代码行为
- mongodb - 如何在分解数组时聚合以允许条目多次计数?
- java - Java Swing 0,0 不在 0,0 处(它在上方和左侧)
- excel - 在 ActiveX 控件的 sub 中无法识别公共变量
- swift - SwiftUI:仅当输入不为空时才启用保存按钮