首页 > 解决方案 > 如何防止 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)

显然,无法捕获该错误。有没有办法防止这种情况?

标签: javaandroid

解决方案


如果您使用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));          

推荐阅读