• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing dates in Java

 
Anthony Palazzo
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chan Go,
Your post was moved to a new topic.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic