Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using and comparing dates 1

Status
Not open for further replies.

LittleRedHat

Instructor
Apr 20, 2001
202
GB
I'm at the planning stage for writing a Java application. I have a super class that along with other information includes an expiry date. At some stage I will need to check this against an input date, which will need to be the current date. I have been reading up on dateFormat and Calendar, but am struggling to see how to apply the concepts and would be very appreciative of guidance.

What type should the expiry date variable be? I currently have it as a string.
Can I and how do I have the application automatically apply the current date?
How do I then check the the current date against the expiry date so that if the expiry date has passed I can include an error message?

Hoping all this isn't too much to ask.

WTA

LRH
 
Hi,
One possible solution, I would suggest making your expiry date as a java.util.Date object and pass it into a method like this:
/**
* <P> isToday()
* This method checks to see if the date is today.
* @param Date
* @return boolean
*/
public boolean isToday(Date dt) {
Calendar now = Calendar.getInstance();
boolean dateIsToday = false;
SimpleDateFormat fm = new SimpleDateFormat(&quot;yyyyMMdd&quot;);
try {
if (fm.format(now.getTime()).equals(fm.format(dt))) {
dateIsToday = true;
} else {
dateIsToday = false;
} // end if
} catch (Exception e) {
System.out.println(&quot;Error: Cannot parse date.&quot;);
}
return dateIsToday;
} // end isToday()

Second, you may want to check out Java's API Documentation (JDK 1.3x)'s SimpleDateFormat class for sample codes, they are very useful ...

Code Sample:
SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, &quot;PST&quot;);
pdt.setStartRule(DateFields.APRIL, 1, DateFields.SUNDAY, 2*60*60*1000);
pdt.setEndRule(DateFields.OCTOBER, -1, DateFields.SUNDAY, 2*60*60*1000);

// Format the current time.
SimpleDateFormat formatter
= new SimpleDateFormat (&quot;yyyy.MM.dd G 'at' hh:mm:ss a zzz&quot;);
Date currentTime_1 = new Date();
String dateString = formatter.format(currentTime_1);

// Parse the previous string back into a Date.
ParsePosition pos = new ParsePosition(0);
Date currentTime_2 = formatter.parse(dateString, pos);

 
Many thanks, jyip, for going to all that trouble for me.

I need to take time out to study your advice and try to work out how to incorporate it with the rest of my program. I'm not much past Java Chapter 1 as yet!

Regards

LRH
 
Thanks again, jyip. Your code has helped start me thinking on the right track.

LRH

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top