1

My date time formatter is , "yyyy-MM-DD"

 SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-DD")

I want to check the date is later than today's date or not. I checked it using this validation.

if(dateFormatter.format(given_Date).compareTo(dateFormatter.format(new Date())) > 0){ ...}

But every time this returns false when the given date is later or not. Can anyone help with this me, please?

chamzz.dot
  • 607
  • 2
  • 12
  • 24
  • try this https://stackoverflow.com/questions/2592501/how-to-compare-dates-in-java – Ali Amini Jan 11 '21 at 06:07
  • 2
    Does this answer your question? [How to check if a date is greater than another in Java?](https://stackoverflow.com/questions/19109960/how-to-check-if-a-date-is-greater-than-another-in-java) – Sudhir Ojha Jan 11 '21 at 06:08
  • Try fixing the **typo**: `DD` *(day in year)* should be `dd` *(day in month)*, otherwise string comparison won't compare correctly. – Andreas Jan 11 '21 at 07:19
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jan 11 '21 at 18:50
  • I cannot reproduce. I tried with Jan 10, Jan 12, Feb 1 and Apr 10 2021, and your code gave the expected result in all cases. – Ole V.V. Jan 11 '21 at 19:47

2 Answers2

3

tl;dr

You asked:

check the date is later than today's date

LocalDate                            // Represent a date-only value, without time-of-day and without time zone or offset-from-UTC.
.parse( "2020-01-23" )               // No need to specify formatting pattern when parsing a string in standard ISO 8601 format. Returns a `LocalDate` object.
.isAfter                             // Compare one `LocalDate` object to another.
(
    LocalDate.now                    // Capture the current date as seen in a particular time zone.
    (
        ZoneId.of( "Africa/Tunis" )  // or: ZoneId.systemDefault()
    )                                // Returns a `LocalDate` object.
)                                    // Returns `boolean`.

Details

Modern solution uses java.time classes, specifically java.time.LocalDate. Compare with isAfter method. You are using terrible date-time classes that were years ago supplanted by java.time.

No need to specify a formatting pattern. Your input strings comply with the ISO 8601 standard used by default in java.time.

By the way, formatting codes are case-sensitive, and day-of-month is dd rather than the DD you used. So the formatting pattern used here by default is akin to uuuu-MM-dd.

boolean isFuture = LocalDate.parse( "2020-01-23" ).isAfter( LocalDate.now() ) ;

Better to explicitly specify desired/expected time by which to determine today’s date. If omitted, the JVM’s current default time zone is implicitly applied.

boolean isFuture = LocalDate.parse( "2020-01-23" ).isAfter( LocalDate.now( ZoneId.of( "America/Edmonton" ) ) ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

If you can work with the variable givenDate as a String there is another way. Check out my code:

import java.util.Calendar;

public class compareDates {
public static void main(String[] args){

   Calendar c = Calendar.getInstance();
   String givenDate = "2021-01-10";
   boolean later = false;

   int yr_now = c.get(Calendar.YEAR);
   int m_now = c.get(Calendar.MONTH) + 1;
   int day_now = c.get(Calendar.DAY_OF_MONTH);

   int given_yr = Integer.parseInt(givenDate.substring(0,4));
   int given_m = Integer.parseInt(givenDate.substring(5,7));
   int given_day = Integer.parseInt(givenDate.substring(8,10));

   //is "given date" later than today's date?
   if(yr_now > given_yr) {
      System.out.print(later);
   }
   else if (yr_now == given_yr && m_now > given_m){
      System.out.print(later);
   }
   else if (m_now == given_m && day_now >= given_day){
      System.out.print(later);
   }
   else {later = true; System.out.print(later);}
}}
Gass
  • 7,536
  • 3
  • 37
  • 41
  • 1
    These terrible date-time classes were supplanted years ago by the *java.time* classes defined in JSR 310. Sun, Oracle, and the JCP community gave up on these classes. So should we all. – Basil Bourque Jan 11 '21 at 17:01
  • I understand your view. But, what's wrong about using them for a case which fulffils its purpose? – Gass Jan 11 '21 at 18:08
  • 1
    It’s hard to convince oneself that this code is correct. Doing date logic by hand os a bad habit since it is error-prone and more complicated than we first expect. It’s best to leave it to java.time. – Ole V.V. Jan 11 '21 at 18:49
  • 1
    One thing wrong is that `Calendar` represents a moment, a date with time-of-day in the context of a time zone. But the Questions calls for a date-only value. So this type is not appropriate to the problem at hand. Another problem is that you’ve ignored the crucial issue of time zone in determining the current date. For any given moment, the date varies around the world by time zone, tomorrow in the East while yesterday in the west. Lastly, doing all that substring manipulation with unproven code seems silly when we have available a one-liner using the proven *java.time* classes. – Basil Bourque Jan 11 '21 at 19:51
  • As a possibly minor point you are providing no validation. If I set `givenDate` to `"555555555555555555"`, your code will process it and give a nonsense answer without noticing that anything is wrong. – Ole V.V. Jan 11 '21 at 20:00