1

I have a date coming in this format -

2015-4-10T11:20:56

I need to validate the date and make sure date it is not greater than current date. Meaning if today is April 10th, then it should not be April 11th or greater than that.

String abc = "2015-4-10T11:20:56";

if(abc is greater than todays date) {
    // log an error
}

How can I do this?

UPDATE:-

I tried parssing like this but it didn't worked -

    String abc = "2015-4-10T11:20:56";
    SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
    try {
        format.parse(abc);
    } catch (ParseException e) {
        e.printStackTrace();
    }
john
  • 11,311
  • 40
  • 131
  • 251

3 Answers3

1

You can try like this using compareTo

Date date = null;
String str = "2015-4-10T11:20:56";
try {
    DateFormat f = new SimpleDateFormat("yyyy-M-d'T'HH:mm:ss");
    f.setLenient(false);
    date = f.parse(str);
    if (date.compareTo(new Date()) > 0) {
      // your code
     }
} catch (ParseException e) { 
    e.printStackTrace();
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

You have to convert the string to a date object. You can use a SimpleDateFormat.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d'T'HH:mm:ss");
Date date = sdf.parse(dateStr);
if (date.compareTo(new Date()) > 0) {
    // log an error    
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
1

This should work for you:

    String abc = "2015-4-10T11:20:56";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
    Date  mydate = df.parse(abc);

    Calendar c = Calendar.getInstance();
    c.setTime(mydate);
    Calendar today = Calendar.getInstance();
    if (c.compareTo(today)>=0){

    }
Jens
  • 67,715
  • 15
  • 98
  • 113