Say a month end date is the date in a month which is the last non-weekend and non-holiday day in that month. How can I find the most recent past month end date with Joda time? For example, the answer for today would be Friday 28th May because that was May's month end and May was the most recent month to end.
DateTime.dayOfMonth.getMaximumValue() gives the last day of the month. Get the weekday of that day to check whether it is in the weekend.
Generally speaking:
- Find current month
- Go back a month
- Start from last day of that month:
- If it's neither a weekend nor a holiday, that's the end date
- Otherwise, go back a day and repeat
Or maybe it's:
- Start from today:
- If it's neither...
This isn't the most efficient, but it's cheap to cache the value once you compute it, because it'll be valid for a whole month. You can easily compute "all" month end dates and store it in a lookup table too. You definitely want to compute when the next one will be, because that's when the current cached value expires.
Example
Here's a snippet I quickly concocted:
import org.joda.time.*;
public class LastMonthEnd {
static int count = 0;
static boolean isWeekendOrHoliday(DateTime d) {
return (count++ < 5);
}
public static void main(String[] args) {
DateTime d = new DateTime().minusMonths(1).dayOfMonth().withMaximumValue();
while (isWeekendOrHoliday(d)) {
d = d.minusDays(1);
}
System.out.println(d);
}
}
Today (2010-06-14 12:04:57Z
), this prints "2010-05-26T12:00:42.702Z"
. Note that isWeekendOrHoliday
is just a stub for an actual implementation. I'd imagine that the real test will be rather complicated (the holiday part), and may be worth a question on its own.