Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To check if the date is after the specified date?

Tags:

java

date

I am trying to do validation for date which should take only current and future dates,if the date is older date then it should show

The date is older than current day

I want to allow the current date also.Right now while giving current day as gievnDate,its always showing

The date is older than current day

But I am expecting an output as

The date is future day for givenDate as today.

Below is the code which I have been trying:

    Date current = new Date();
    String myFormatString = "dd/MM/yy";
    SimpleDateFormat df = new SimpleDateFormat(myFormatString);
    Date givenDate = df.parse("15/02/13");
    Long l = givenDate.getTime();
    //create date object
    Date next = new Date(l);
    //compare both dates
    if(next.after(current) || (next.equals(current))){
        System.out.println("The date is future day");
    } else {

        System.out.println("The date is older than current day");
    }

Here when I am checking with 15/02/13,its showing as older than current day.Is my method wrong?or Is there any better approaches?

like image 973
Prabhath kesav Avatar asked Feb 15 '13 10:02

Prabhath kesav


2 Answers

if(next.after(current) && (next.equals(current))) is always false because next can't be strictly after current AND equal to current at the same time.

You probably meant:

if(next.after(current) || (next.equals(current))) with an OR.

like image 193
assylias Avatar answered Nov 15 '22 01:11

assylias


tl;dr

LocalDate                                      // Represents a date-only, without time-of-day and without time zone.
.parse( 
    "15/02/13" , 
    DateTimeFormatter.ofPattern( "dd/MM/uu" )  // Specify a format to match you're input.
)                                              // Returns a `LocalDate` object.
.isBefore(                                     // Compare one `LocalDate` to another.
    LocalDate.now(                             // Capture the current date…
        ZoneId.of( "America/Montreal" )        // …as seen through the wall-clock time used by the people of a particular region (a time zone).
    )                                          // Returns a `LocalDate` object.
)                                              // Returns a boolean.

Details

The other answers are correct about your error in the boolean logic.

Also, you are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.

That mentioned boolean logic is easier with the isBefore & isAfter methods on java.time.LocalDate class.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

DateTimeFormatter

To parse an input string as a date-time value, use the DateTimeFormatter class.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uu" );
String input = "15/02/13";
LocalDate ld = LocalDate.parse( input , f );

Compare

To compare LocalDate objects, you can call methods such as compareTo, equals, isAfter, isBefore, isEqual.

String message = "ERROR - Message not set. Error # f633d13d-fbbc-49a7-9ee8-bcd1cfa99183." ;
if( ld.isBefore( today ) ) {  // Before today.
   message = "The date: " + ld + " is in the past, before today: " + today );
} else if( ld.isEqual( today ) ) {  // On today.
   message = "The date: " + ld + " is today: " + today );
} else if( ld.isAfter( today ) ) {  // After today.
   message = "The date: " + ld + " is in the future, later than today: " + today );
} else {  // Double-check.
   message = "ERROR – Unexpectedly reached Case Else. Error # c4d56437-ddc3-4ac8-aaf0-e0b35fb52bed." ) ;
}

Formats

By the way, the format of your input string lacking the century is ill-advised. Using two digits for the year makes dates harder to read, creates more ambiguity, and makes parsing more difficult as various software behave differently when defaulting the century. We can now afford the two extra digits in modern computing memory and storage.

When serializing date-time values to text, stick with the practical and popular ISO 8601 standard formats. For a date-only that would be YYYY-MM-DD such as 2016-10-22.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

like image 25
Basil Bourque Avatar answered Nov 15 '22 01:11

Basil Bourque