I recovered an old post from 2012 on my previous blog. Here I translated and updated the post.
Working with dates is not an easy task in a programming language. Usually, because there is no standard (like it happens on databases) or sometimes, the standard is not implemented. On 2012 I talked that joda time was planned to be the new data standard on Java, and in fact, in 2015, Joda time is the facto standard ( as they claim on their site):
Joda-Time is the de facto standard date and time library for Java. From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).
I was interested in doing some calculations to check if a time point was inside a time interval or not. This is useful when implementing all Allen time operations. Here you will find the original paper from the ’82 And some more friendly approaches here: - Allen’s algebra. - More Allen’s time intervals..
Working with dates on Joda time is really easy:
String startDate = "18/09/2012";
String endDate = "22/09/2012";
// datetime formatter, allows to read and write strings
= new DateTimeFormatterBuilder().
DateTimeFormatter dtf appendDayOfMonth(2).
appendLiteral("/").
appendMonthOfYear(2).
appendLiteral("/").
appendYear(4, 4).toFormatter();
= dtf.parseDateTime(startDate);
DateTime start = dtf.parseDateTime(endDate);
DateTime end
int months = Months.monthsBetween(start, end).getMonths();
= lastRule.plusDays(28);
DateTime newdate for(int i=0;i<months;i++){
= lastRule.plusDays(28);
newdate }
= new Interval(start,end);
Interval interval if(interval.contains(newdate)){
.setText(
jTextArea2"That day is included: "
+ dtf.print(newdate));
}else{
.setText(
jTextArea2"The day is not included: "
+ dtf.print(newdate));
}