Friday the 13th with Joda Time

I’ve always wanted to try Joda Time and in this post I’d like to present some code that finds Friday the 13th dates. Wouldn’t it be interesting to know when the next Friday the 13th is or which year has got the most occurrences of this particular day?

The Eclipse project with the code for this post can be downloaded as tar.gz or zip. You can browse the code online here.

The code

Using Joda Time it’s super easy to iterate over the next days using the plusDays method of DateTime. Finding Friday the 13th dates is straight forward this way. Sure, we could optimize it but Joda Time seems to be really fast so there’s no need to do this.

public static List<DateTime> getNextNthFriday13th(final int n) {
  final List<DateTime> fridays = new ArrayList<DateTime>();
 
  DateTime dt = new DateTime();
  int curN = 0;
  while (curN < n) {
    dt = dt.plusDays(1);
 
    if (dt.getDayOfMonth() != 13) continue;
    if (dt.getDayOfWeek() != DateTimeConstants.FRIDAY) continue;
 
    fridays.add(new DateTime(dt.toInstant()));
    curN++;
  }
 
  return fridays;
}

Finding the next year with the most Friday the 13th dates is simple too. Just get the next n occurrences of Friday the 13th and sort them by year to find the one with the highest amount. Another way to solve this is this: just search the next year that has got three Friday the 13th dates and you’re done. Have a look at the code of this method to see my quick solution.

Conclusion

It’s a real joy to use Joda Time because its API has got methods for a lot of use cases. Although I haven’t done any performance tests yet it seems to be lightning fast. I recommend that you should definitely have a look at it.