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