• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

camparison of YEAR attibute of Calendar

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
userCalendar.setTime(deliveryDate);


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: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
reply
    Bookmark Topic Watch Topic
  • New Topic