Using Java validate date is not in the future

Hello,

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"
cgray1223Asked:
Who is Participating?
 
for_yanCommented:


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();

if(dd2.before(dd1)){
then your s1 date is in the future
}
0
 
Gurvinder Pal SinghCommented:
using SimpleDateFormat, you will convert that time to a Date object
http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm

convert that date object to milliseconds
http://www.java-examples.com/convert-date-milliseconds-example

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
0
 
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");
df.setTimeZone(TimeZone.getTimeZone("GMT"));

Date testDate = df.parse(testDateStr);

if(testDate.after(new Date()))
{
    System.out.println("testDate is later than NOW");
}
else
{
    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.
0
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.