猿问

使用日期类将给定日期的字符串与当前日期进行比较时获取空对象引用异常

我想在这里检查两个日期,如果两个日期相等,那么计时器应该运行,否则不运行。所以,要检查我是否在这里使用了两个字符串,一个是我提供的给定日期,另一个是我使用的日期类获取当前日期。我试图比较两个日期:


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

    }


慕娘9325324
浏览 119回答 4
4回答

繁花如伊

int compareToNow(String date){&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Date date1 = Calendar.getInstance().getTime();&nbsp; &nbsp; &nbsp; &nbsp; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");&nbsp; &nbsp; &nbsp; &nbsp; Date d1= format.parse(format.format(date1));&nbsp; &nbsp; &nbsp; &nbsp; Date d2=format.parse(date);&nbsp; &nbsp; &nbsp; &nbsp; return d1.compareTo(d2);&nbsp; &nbsp; } catch (ParseException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; }}d1=d2返回“0”d1>d2返回“1”d1<d2返回“-1”

青春有我

您可以使用 Date 类的 after 和 before 方法。if(!yourfirstDate.after(yourSecondDate) && !yourSecondDate.before(yourfirstDate)) {&nbsp; //if it comes here, you can code here}

白猪掌柜的

尝试这个:&nbsp;var x =new&nbsp; Date("March 21, 2012"); //date to be compared&nbsp;var y =new&nbsp; Date; //current date&nbsp;console.log(x==y) //evolves false&nbsp;console.log(x!=y)&nbsp; //evolves true

慕后森

在 Java 中,Date 具有可用于比较两个给定日期的 after 和 before 方法。如下所示:if(!date.after(date1) && !date1.before(date)) {&nbsp; &nbsp; &nbsp; //if it comes here, it means dates are equal.}
随时随地看视频慕课网APP

相关分类

Java
我要回答