13

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

kype
  • 555
  • 1
  • 6
  • 24
  • 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? – Dawood ibn Kareem Nov 01 '13 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). – kype Nov 01 '13 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](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 16 '21 at 05:15

7 Answers7

11

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() ));
Community
  • 1
  • 1
rolfl
  • 17,539
  • 7
  • 42
  • 76
  • Thanks. Will that store the current time information into the date too? – kype Nov 01 '13 at 11:48
  • Yes it will, which you can remove if you need to. – rolfl Nov 01 '13 at 11:49
  • I have to put it into calender in order to modify the time right? Since the Date.setHour has been depreciated – kype Nov 01 '13 at 11:54
  • Why do you want to modify the time? – Dawood ibn Kareem Nov 01 '13 at 11:55
  • 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 – kype Nov 01 '13 at 11:56
  • See http://stackoverflow.com/questions/1439779/how-to-compare-two-dates-without-the-time-portion – rolfl Nov 01 '13 at 11:59
  • But because you used the `"dd-MM-yyyy"` formatter to parse `myDate`, it doesn't matter what the time is in `todayDate`. – Dawood ibn Kareem Nov 01 '13 at 11:59
  • @ David Wallace. Thanks. Yes myDate is in 00:00:00 time. Setting todayDate = new Date(); to the same 00:00:00 time is the problem im facing @ rolfl Will look into joda. Since this is a somewhat small application was expecting java calender api's to provide the neccessary. Guess it cant – kype Nov 01 '13 at 12:03
  • Yes, it can. Can you answer my question in the comment under your question? Then I'll post a solution that doesn't need Joda. – Dawood ibn Kareem Nov 01 '13 at 12:08
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);
 }
ThmHarsh
  • 601
  • 7
  • 7
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.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
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();
                        }
 } }
Prajwal Waingankar
  • 2,534
  • 2
  • 13
  • 20
1

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

so:

    Date currentDate = new Date();

will do the job

Gigalala
  • 439
  • 1
  • 8
  • 24
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

Ahmet Karakaya
  • 9,899
  • 23
  • 86
  • 141
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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161