15

Hi im trying to compare a user inputted date (as a string) with the current date so as to find out if the date is earlier or older.

My current code is

String date;
Date newDate;
Date todayDate, myDate;     
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy");

while(true)
{
    Scanner s = new Scanner (System.in);
    date = s.nextLine();
    Calendar cal = Calendar.getInstance();
    try {
        // trying to parse current date here
        // newDate = dateFormatter.parse(cal.getTime().toString()); //throws exception

        // trying to parse inputted date here
        myDate = dateFormatter.parse(date); //no exception
    } catch (ParseException e) {
        e.printStackTrace(System.out);
    }

}

Im trying to get both user input date and current date into two Date objects, so that i can use Date.compareTo() to simplify comparing dates.

I was able to parse the user input string into the Date object. However the current date cal.getTime().toString() does not parse into the Date object due to being an invalid string.

How to go about doing this? Thanks in advance

3
  • Just to clarify - you want something that will return true if the entered date is yesterday, but false if the entered date is today. Is that right? Commented Nov 1, 2013 at 12:04
  • Yes thats what im trying to do. Assuming im running the program today, newDate = new Date(); gives me (1 Nov 2013 8pm) and if the user input 1 Nov 2013, it should return false as the entered date is today (regardless of time). Commented Nov 1, 2013 at 12:10
  • For new readers to this question 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. Commented Apr 16, 2021 at 5:15

7 Answers 7

12

You can get the current Date with:

todayDate = new Date();

EDIT: Since you need to compare the dates without considering the time component, I recommend that you see this: How to compare two Dates without the time portion?

Despite the 'poor form' of the one answer, I actually quite like it:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.format(date1).equals(sdf.format(date2));

In your case, you already have:

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy");

so I would consider (for simplicity rather than performance):

todayDate = dateFormatter.parse(dateFormatter.format(new Date() ));
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks. Will that store the current time information into the date too?
Yes it will, which you can remove if you need to.
I have to put it into calender in order to modify the time right? Since the Date.setHour has been depreciated
Why do you want to modify the time?
Because i just want to compare the user input date to current date based on date only (not time). compareTo() compares the time also, hence i want to set the time to 00:00:00 to remove the time comparison issue
|
4

Here is the code to check if given date-time is larger then the Present Date-time.Below method takes perticular date-time string as argument and returns true if provided date-time is larger then the present date-time. #thmharsh

private boolean isExpire(String date){
    if(date.isEmpty() || date.trim().equals("")){
        return false;
    }else{
            SimpleDateFormat sdf =  new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss a"); // Jan-20-2015 1:30:55 PM
               Date d=null;
               Date d1=null;
            String today=   getToday("MMM-dd-yyyy hh:mm:ss a");
            try {
                //System.out.println("expdate>> "+date);
                //System.out.println("today>> "+today+"\n\n");
                d = sdf.parse(date);
                d1 = sdf.parse(today);
                if(d1.compareTo(d) <0){// not expired
                    return false;
                }else if(d.compareTo(d1)==0){// both date are same
                            if(d.getTime() < d1.getTime()){// not expired
                                return false;
                            }else if(d.getTime() == d1.getTime()){//expired
                                return true;
                            }else{//expired
                                return true;
                            }
                }else{//expired
                    return true;
                }
            } catch (ParseException e) {
                e.printStackTrace();                    
                return false;
            }
    }
}


  public static String getToday(String format){
     Date date = new Date();
     return new SimpleDateFormat(format).format(date);
 }

Comments

2

You can do this.

// Make a Calendar whose DATE part is some time yesterday.
Calendar cal = Calendar.getInstance();
cal.roll(Calendar.DATE, -1);

if (myDate.before(cal.getTime())) {
    //  myDate must be yesterday or earlier
} else {
    //  myDate must be today or later
}

It doesn't matter that cal has a time component, because myDate doesn't. So when you compare them, if cal and myDate are the same date, the time component will make cal later than myDate, regardless of what the time component is.

Comments

2
 public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.

for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){

SimpleDateFormat sdf1234 = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
                    String abs12 = value.getExpiryData();

                    Date todayDate = new Date();

                    try {
                        Date testDate1 = sdf1234.parse(abs12);

                        if(testDate1.compareTo(todayDate) <0){//  expired
                            dataSnapshot1.getRef().removeValue();
                        }
                        else if(testDate1.compareTo(todayDate)==0){// both date are same
                            if(testDate1.getTime() == todayDate.getTime() || testDate1.getTime() < todayDate.getTime())
                            {//  expired
                                dataSnapshot1.getRef().removeValue();
                            }
                            else
                                {//expired
                                //Toast.makeText(getApplicationContext(),"Successful praju ",Toast.LENGTH_SHORT).show();
                            }
                        }else{//expired
                           // Toast.makeText(getApplicationContext(),"Successful praju ",Toast.LENGTH_SHORT).show();
                        }
 } }

Comments

1

Creating a new Date() will give you a Date object with the current date.

so:

    Date currentDate = new Date();

will do the job

Comments

0

Fomat does not comply as you expect.

 Calendar cal = Calendar.getInstance();
      System.out.println(cal.getTime().toString());

output : Fri Nov 01 13:46:52 EET 2013

Comments

0

java.time

I recommend that you use java.time, the modern Java date and time API, for your date work.

    ZoneId zone = ZoneId.of("America/Santarem");
    LocalDate today = LocalDate.now(zone);
    
    String userInput = "14-04-2021";
    LocalDate myDate = LocalDate.parse(userInput, DATE_PARSER);
    
    if (myDate.isBefore(today)) {
        System.out.println(userInput + " is in the past.");
    } else if (myDate.isAfter(today)) {
        System.out.println(userInput + " is in the future.");
    } else {
        System.out.println(userInput + " is today.");
    }

Output is:

14-04-2021 is in the past.

I used this formatter for parsing:

private static final DateTimeFormatter DATE_PARSER
        = DateTimeFormatter.ofPattern("dd-MM-uuuu");

What went wrong in your code?

I commented the line back in from which you got the exception:

            // trying to parse current date here
            newDate = dateFormatter.parse(cal.getTime().toString()); //throws exception

And sure enough I got this exception:

java.text.ParseException: Unparseable date: "Fri Apr 16 07:37:00 CEST 2021"

Your SimpleDateFormat tries to parse a string in the format dd-MM-yyyy. cal.getTime() returns a Date, and the value from toString() on a Date looks like what the the exception says, Fri Apr 16 07:37:00 CEST 2021. This is not in dd-MM-yyyy format (not even close). This is why the parsing fails with the exception you saw.

Using java.time there’s no point in parsing today’s date at all since you did not get it as a string. Using the old and troublesome date classes from Java 1.0 and 1.1 it could be used as a hack to get rid of the time part of the Date, but it wasn’t the recommended way back then either.

Link

Oracle tutorial: Date Time explaining how to use java.time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.