Prabhath kesav
Prabhath kesav

Reputation: 428

To check if the date is after the specified 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?

Upvotes: 7

Views: 51072

Answers (5)

Basil Bourque
Basil Bourque

Reputation: 338211

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 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.

Upvotes: 6

Naxos84
Naxos84

Reputation: 2028

Eventhough this is an old question.
I'd like to share an easy solution.
You can check if the current date is NOT before the next Date. Because if it is not before it is either equals the current Date or after the current Date. And that is what you are looking for. So you don't need the "OR equals" check.

if(!current.isBefore(next)){
     System.out.println("The date is future day");
}else{
     System.out.println("The date is older than current day");
}

Alternatively you could even use:

if(next.getTime() >= current.getTime())

Upvotes: -2

Andreas Dolk
Andreas Dolk

Reputation: 114757

Apart from the logic error that the assylias pointed out:

You don't specify a time so givenDate is "15/02/13 00:00:00.000" in your example. Now, if you compare that given date to any real timestamp on the same day (aka "now"), then the givenDate is almost always "older" then "now".

Set givenDate to the last millisecond of that day and you won't need the "equals" test.

Upvotes: 3

user
user

Reputation: 6947

There is at least one bug in this code, but I don't see how it would throw an exception. The statement:

if(next.after(current) && (next.equals(current))){

will never evaluate to true, because presumably, next.after(current) and next.equals(current) are not both true at the same time.

You probably meant to write:

if(next.after(current) || (next.equals(current))){

Also, it is usually a good idea to at least include specific details of the error: on which exact line does the exception get thrown (if that is indeed what you meant), and what is the exact output (even if that output is an exception) given what input?

Upvotes: 2

assylias
assylias

Reputation: 328568

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.

Upvotes: 9

Related Questions