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.
Joda-Time is the most widely used date and time processing library, before the release of Java 8. Its purpose was to offer an intuitive API for processing date and time and also address the design issues that existed in the Java Date/Time API.
So the short answer to your question is: YES (deprecated).
The Julian calendar defines a leap year as once every four years. This becomes inaccurate over time, to such an extent that by 1582, 10 days had to be 'lost' to correct the calendar. The Julian calendar is represented in Joda-Time by the Julian chronology. This chronology applies Julian rules for all time.
Adjusting Time ZoneUse the DateTimeZone class in Joda-Time to adjust to a desired time zone. Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone). Use proper time zone names.
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:
Or maybe it's:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With