【发布时间】:2020-03-31 23:27:03
【问题描述】:
我有这个方法应该取两次之间的差异,但我在 try 块的第一行代码中不断收到空指针异常。
time参数以“HH:mm:ss”格式获取函数调用的时间,time1和time2都是“HH:mm:ss”格式的全局字符串变量。
private String calculateTime(String time) {
time2 = time;
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Date date1;
Date date2;
try {
date1 = timeFormat.parse(time1);
date2 = timeFormat.parse(time2);
long diff = date2.getTime() - date1.getTime();
time1 = timeFormat.format(new Date(diff));
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("The diff is "+ time1);
return time1;
}
}
我已经单步执行了代码,一切似乎都设置正确,只有当它到达date1 = timeFormate.parse(time1) 时它似乎不起作用。有谁知道我可能做错了什么?
【问题讨论】:
-
除了空指针异常之外,当您将毫秒间的差异转换回
Date时,这将出现严重错误。两个日期之间的差异作为Date没有意义。这是一件非常糟糕的事情。 -
什么是
time1?它在哪里声明?并初始化? -
向我们展示完整的堆栈跟踪。
标签: java nullpointerexception time-format