有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android SimpleDataFormat快疯了

我在Android中使用SimpleDateFormat方法时遇到了一个奇怪的问题。有时(很少)format方法返回格式错误的日期。这是代码,下面是输出。你能解释一下原因吗

代码如下:

  public class MyObject{

    protected Timestamp detectionDate;

    public String getDetectionDateAsString() {
      String dateAsString =  Constant.ISO_8601_TS_DF.format(detectionDate);
      if(dateAsString.length()>19){
        logger.warn("ERROR ON FORMAT DATE");
        logger.warn("dateAsString:" + dateAsString);
        logger.warn("detectionDate:" + detectionDate);
      }
    }
  }

  public class Constant {

    public static final SimpleDateFormat ISO_8601_TS_DF = 
              new  SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  }

输出:

14:35:05.150 [AsyncTask #2] WARN  i.m.t.d.o.OutcomesTableData - ERROR ON FORMAT DATE
14:35:05.150 [AsyncTask #2] WARN  i.m.t.d.o.OutcomesTableData - dateAsString:2016-0007-0001 0000:00:0000
14:35:05.151 [AsyncTask #2] WARN  i.m.t.d.o.OutcomesTableData - detectionDate:2016-07-03 12:34:27.194

多谢各位


共 (2) 个答案

  1. # 1 楼答案

    TimeStamp类已经返回指定格式的字符串(请查看TimeStamp类中的TIME_FORMAT_REGEX字段),因此调用toString()方法将返回所需格式的字符串

  2. # 2 楼答案

    TimestampDate的扩展,根据docs

    The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.

    要解决您的问题,您可以尝试改用Calendar

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(timestamp.getTime());
    String format = dateFormat.format(cal.getTime());