-4

I have a date string of the form "07-AUG-13".

I want to know whether the given date is within a certain period from the current date or not.

bool 
isItWithin(int period){
    //check if "07-AUG-13" is within a "period" months from now
}
Theolodis
  • 4,977
  • 3
  • 34
  • 53
VJS
  • 2,891
  • 7
  • 38
  • 70
  • any effort from your side? – Ruchira Gayan Ranaweera Oct 14 '14 at 08:32
  • Have you tried anything so far? – MrHug Oct 14 '14 at 08:32
  • Hint: Use `java.util.Calendar` to do this. – Jens Oct 14 '14 at 08:33
  • I have so many approach on net but confused. People have used joda, util.calender etc. Can you help me using util.Calender – VJS Oct 14 '14 at 08:35
  • or another hint you could think of date in millis and do arithmetic on it to find if its within 3/6/9 months range. – SMA Oct 14 '14 at 08:36
  • possible duplicate of [How to get next month start date and end date if current month is february?](http://stackoverflow.com/questions/23493196/how-to-get-next-month-start-date-and-end-date-if-current-month-is-february). And [this](http://stackoverflow.com/q/10828398/642706) and many others. – Basil Bourque Oct 14 '14 at 08:36
  • I have seen this link and trying to understand the ans given by @Juvanis. But didn't get that. if ((year1 * 12 + month1) - (year2 * 12 + month2) > 6) logic – VJS Oct 14 '14 at 08:38
  • possible duplicate of [Java Date month difference](http://stackoverflow.com/questions/1086396/java-date-month-difference) – Juru Oct 14 '14 at 08:45

3 Answers3

1

Using the Calendar class:

  public static boolean isWithinMonths(Date startDate, Date endDate, int months) {
    Calendar startCalendar = Calendar.getInstance();
    startCalendar.setTime(startDate);
    Calendar endCalendar = Calendar.getInstance();
    endCalendar.setTime(endDate);

    startCalendar.add(Calendar.MONTH, months);

    return startCalendar.before(endCalendar);
  }
PeterK
  • 1,697
  • 10
  • 20
0

If you use Java 8 use the new time api.

LocalDate startDate = LocalDate.of(2004, Month.JANUARY, 1);
LocalDate endDate = LocalDate.of(2005, Month.JANUARY, 1);

long monthsInYear2 = ChronoUnit.MONTHS.between(startDate, endDate);
Juru
  • 1,623
  • 17
  • 43
-2

i recommend you to use [Joda Time Library] instead of JDK<8 [Joda...]

or you can try this stuff:

long diff = date1.getTime() - date2.getTime();
long monthDiff=Math.ceil((diff / (60 * 60 * 24)));