Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

camparison of YEAR attibute of Calendar  RSS feed

Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i am using a piece of java script to get a GUI display for a user to select a date for an application i am working on.
what i then want to do is to test whether the date selected is plus or minus one year of the current date.

the users date is saved in Date format, but i am unable to isolate the YEAR attribute when converting it to a Calendar object. this is what iv tried so far:

deliveryDate = dateFormat.parse(deliveryDateStr); // the user inputted date

Calendar currentCalendar = new GregorianCalendar();

Calendar userCalendar = new GregorianCalendar();

if (userCalendar.get(Calendar.YEAR) > currentCalendar.get(Calendar.YEAR+1) || userCalendar.get(Calendar.YEAR) < currentCalendar.get(Calendar.YEAR-1)) {
throw new ParseException("Year out of bounds.", 1);

any ideas?
Java Cowboy
Posts: 16080
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what you're doing wrong:

currentCalendar.get(Calendar.YEAR+1) should be: currentCalendar.get(Calendar.YEAR) + 1
currentCalendar.get(Calendar.YEAR-1) should be: currentCalendar.get(Calendar.YEAR) - 1

But even if you change this, your method is most likely not going to do what you expect it to do (check if the date entered is within one year from now into the past or the future). Looking at just the year isn't enough. What if today is January 10, 2007 and the user enters December 10, 2006? These dates are only a month apart, but your application is going to complain that the dates are too far apart.
[ August 20, 2007: Message edited by: Jesper Young ]
We can walk to school together. And we can both read this tiny ad:
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!