This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Java in General and the fly likes Comparing dates in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Comparing dates in Java" Watch "Comparing dates in Java" New topic

Comparing dates in Java

Anthony Palazzo

Joined: Oct 09, 2012
Posts: 3
Hi all. I'm relatively new when it comes to Java programming and this will be my first post. I'd like to compare dates by having the user input a specific date and check whether that date is greater than today's date by 7 days. If so, it will then link them to a different screen from the JSP.

I'm getting the current date from a class called "CurrentDateTime".

The method "getDate(String dateFormat)" looks like this:

Any suggestions? Thanks in advance.
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

That getDate() method is not relevant for the task you want to perform. There's no point in having the current date in String format, since you won't be manipulating or comparing it in that format. You'll be doing all that using Date, Calendar, and long.

To do what you want to do, you do the following;

1. Create a GregorianCalendar corresponding to "now".

2. Set the hour, minute, second, and millisecond of that date to 0.

3. Add 7 to the DATE field of that Calendar. That Calendar now represents one week from today, at midnight.

4. Get the user to input a String representing his date.

5. Use SimpleDateFormat to parse that String into a Date object.

6. Create a GregorianCalendar and set it equal to that Date object. (Look at the methods on Date and Calendar--you'll have to go through a long to do it.)

7. Set this Calendar to midnight as you did with the other one.

8. If the Calendar class has methods for comparing greater/less/equal, use them to determine your result. If not, convert back to longs or Dates and then compare.
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

Chan Go,
Your post was moved to a new topic.
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

I agree with Jeff, except there's no reason to reference GregorianCalendar in your code. Calendar.getInstance() will get you an instance of your locale's calendar (probably a GregorianCalendar), but the java.util.Calendar class has all the methods you need, and you'll be programming to the superclass (as opposed to locking in to a specific subclass). Also, there's no need to go through the long to set the time; simply calling setTime and passing in the date will do it nicely.

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
subject: Comparing dates in Java
It's not a secret anymore!