我想在这里检查两个日期,如果两个日期相等,那么计时器应该运行,否则不运行。因此,要检查我是否已获取两个字符串,其中一个是我提供的给定日期,另一个是我使用的日期将获取当前日期的类。我尝试比较两个日期:
Date date1 = new Date();//Fetch currentdate
String dtStart = "2019-02-20";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(dtStart);
} catch (ParseException e) {
e.printStackTrace();
}
我在这里比较两个日期,如果两个日期相等,则计时器应该运行,否则不运行。但是在比较时,我在这里得到空对象引用异常:
if(date.compareTo(date1)== 0) {
timer(diff);
Intent intent = getIntent();
String imageURL = intent.getStringExtra("urlKey");
initViews();
displayImage(imageURL);
setListeners();
}
else
{
Toast.makeText(getApplicationContext(), "Time Expired", Toast.LENGTH_SHORT).show();
}
最佳答案
int compareToNow(String date){
try {
Date date1 = Calendar.getInstance().getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date d1= format.parse(format.format(date1));
Date d2=format.parse(date);
return d1.compareTo(d2);
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
d1
= d2
返回“0”
d1
> d2
返回“1”
d1
<d2
返回“-1”
关于java - 使用 Date 类将给定日期的字符串与当前日期进行比较时出现 Null 对象引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54708012/