代码之家  ›  专栏  ›  技术社区  ›  Hong

如何防止java.util.Date.toString崩溃?

  •  3
  • Hong  · 技术社区  · 7 年前

    偶尔,以下代码会导致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)
    

    显然,这个错误是无法捕捉到的。有没有办法防止这种情况?

    2 回复  |  直到 7 年前
        1
  •  1
  •   crgarridos    7 年前

    很奇怪的问题。。。

    顺便说一下,没有抛出异常,但是 AssertionError Error

    您可以使用以下方法捕获它:

    try {
        (new Date()).toString());
    } catch (AssertionError ex) {// or Error or Throwable
        ...
    }
    
        2
  •  2
  •   ViaTech    7 年前

    如果您使用 新日期() 安卓8 与您的代码相反,您可以使用 java.time公司 爪哇8 而不是 日期类型

    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));