0

I want to check two dates here if both dates are equal then the timer should run else not.So, to check that i have taken two string here one is the given date that i have provided and other date i have used date class that will fetch current date.I have tried to compare both dates:

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

I am comparing here two dates if both dates are equal then the timer should run else not.But while comparing i am getting null object reference exception here:

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();
    }
pratival
  • 111
  • 8
  • `Date date1 = new Date()` will create you the date including not only year, month, day, but also with hour, minute, second, milisecond. And `date.compareTo(date1)` will return `0` only in case if the dates are equal up to the milisecond. – Vladyslav Matviienko Feb 15 '19 at 11:11
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Feb 15 '19 at 13:08
  • first you should convert it second. then compare – Muzaffer Bulut Feb 15 '19 at 12:41
  • For you, pratival, I have written [a brand new answer to the original question that @Android linked to](https://stackoverflow.com/a/54711788/5772882). Since your date string is in ISO 8601 format, you may simplify and not use a `DateTimeFormatter` as in that answer: just do `LocalDate.parse(dtStart)`. – Ole V.V. Feb 15 '19 at 14:56
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 15 '19 at 19:59
  • Always search Stack Overflow before posting. – Basil Bourque Feb 15 '19 at 20:01
  • @OleV.V. Thanks – pratival Feb 16 '19 at 06:13
  • @pratival Another thing, when asking about code that isn’t working, please remember *expected result* and *precisely how observed result differs*. Since these parts are missing, I suspect that the answers below don’t give you what you expected, and none of them explain why your code didn’t work. Quote: “Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. ” https://stackoverflow.com/help/on-topic – Ole V.V. Feb 16 '19 at 06:22
  • @OleV.V.Sure. i have modified the question and i think its clear and understandable now. – pratival Feb 16 '19 at 07:57
  • If you get a NullPointerException when comparing, then one (or both) is `null`. – Mark Rotteveel Feb 16 '19 at 16:40
  • @Mark Rotteveel The string date that i have given that is showing null object exception because while converting string to date its not taking while i tried to print the same string in debug after converting to date its displaying proper date but while comparing two date objects exception occurs. – pratival Feb 16 '19 at 17:57
  • I’d like to help you with that exception if I can. Could you perhaps [create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) so I can see it happening on my computer too? – Ole V.V. Feb 16 '19 at 18:52
  • @Ole V.V You can check simple date format line in my code where i tried to convert a string to date.I think its not converted to date properly i.e null object is compared with current date object so its generating exception – pratival Feb 17 '19 at 03:49
  • No, I cannot reproduce. The first snippet runs without problems. I cannot compile the second snippet because it refers to names (variables) that are not defined. If I paste the if-else statement into the try part of the first snippet, it chooses the `else` part because the date parts are not equal. I see no exception. – Ole V.V. Feb 17 '19 at 03:56
  • @Ole V.V I am not having system now thats why i am explaining you i am getting exception in if condition while comparing two date objects.I dont think my question is asked before here. – pratival Feb 17 '19 at 04:17

4 Answers4

1
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 returns "0"

d1 > d2 returns "1"

d1 < d2 returns "-1"

gencaysahinn
  • 193
  • 2
  • 9
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 15 '19 at 20:01
0

In Java, Date has after and before methods that can be used to compare two given dates. As shown below:

if(!date.after(date1) && !date1.before(date)) {
      //if it comes here, it means dates are equal.
}
Alok Gupta
  • 1,353
  • 1
  • 13
  • 29
0

Try this:

 var x =new  Date("March 21, 2012"); //date to be compared
 var y =new  Date; //current date
 console.log(x==y) //evolves false
 console.log(x!=y)  //evolves true
0

you can use after and before methods of Date class.

if(!yourfirstDate.after(yourSecondDate) && !yourSecondDate.before(yourfirstDate)) {
  //if it comes here, you can code here
}
Shahid Khan
  • 371
  • 2
  • 10