Using Java validate date is not in the future


How can I tell if a date is in the following format is in the future as compared to the current GMT system time

"MM/dd/yy HH:mm:ss"
Who is Participating?

String s1 = "03/27/11 13:05:23");
SimpleDateFormat f = new SimpleDateFormat("MM/dd/yy HH:mm:ss z" );

java.util.Date dd1 = f.parse(s1 + " GMT", new ParsePosition(0));

java.util.Date dd2 = new java.util.Date();

then your s1 date is in the future
Gurvinder Pal SinghCommented:
using SimpleDateFormat, you will convert that time to a Date object

convert that date object to milliseconds

Now, get the current Date time's milliseconds by doing
Date date=new Date() ;    
 System.out.println("Today is " +date.getTime())

if the current time's milliseconds' value is smaller, then the input date was of future time
mccarlIT Business Systems Analyst / Software DeveloperCommented:
You mention that you are comparing GMT time, so you may need something along these lines...

String testDateStr = "03/29/11 04:45:13";

DateFormat df = new SimpleDateFormat("MM/dd/yy HH:mm:ss");

Date testDate = df.parse(testDateStr);

if(testDate.after(new Date()))
    System.out.println("testDate is later than NOW");
    System.out.println("testDate is earlier than NOW");

Open in new window

Note: Line 5 is where you tell the parser to interpret that date that is in the String as a GMT date. Also using the "after" method of Date (on line 9) makes it a bit more obvious exactly what you are checking for.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.