Sunday 1 December 2013

How to calculate if two dates are more than one year appart in Java.

Recently I had to do dates validation. I was passing two dates and I had to make sure that the difference between these dates was not more than one year.

I set up a small Java project using Joda Time library.

Here's my code:

import org.joda.time.DateTime;
import org.joda.time.Months;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class TimeCheck {

    public static void main(String[] args) {

       // half-a-year difference:
       calcTime("20100101", "20100601");

       // nine-months difference:
       calcTime("20100101", "20100901");

      // more-than-a-year difference:
      calcTime("20100101", "20110901");
    }
   
    private static void calcTime (String fromDate, String toDate) {
        DateTimeFormatter dateDecoder = DateTimeFormat.forPattern("yyyyMMdd");

        DateTime startDate = dateDecoder.parseDateTime(fromDate);
        System.out.println("start time: " + startDate.toString());

        DateTime endDate = dateDecoder.parseDateTime(toDate);
        System.out.println("start time: " + endDate.toString());

        Months diff = Months.monthsBetween(startDate, endDate);
        System.out.println("diff is: " + diff.getMonths());

        boolean moreThanYear = diff.isGreaterThan(Months.TWELVE);

        if (moreThanYear) {
            System.out.println("result is: " + moreThanYear);
        }

        // not needed here but I show how to add one year to target date:
        DateTime newEnd = endDate.plusYears(1);
        System.out.println("new end:    " + newEnd.toString()); 
    }
}

No comments:

Post a Comment