I have a list of holidays in a year. I need the following things.
I need to get all the dates in a year. Then I need to remove all the holidays and get the remaining dates. Something like:
Get dates (all dates in a year)
Get holiday dates (I already have them stored in a database)
Get dates - holiday dates
Against a particular date, I need to know what day it is (Monday? Tuesday? What day?)
QUESTION:-
Using the Joda-Time library, please share the simplest way of getting it done.
Answer to first question:
public static List<LocalDate> getDaysOfYear(int year, List<LocalDate> holidays) {
LocalDate date = new LocalDate(year, 1, 1);
LocalDate end = new LocalDate(year + 1, 1, 1);
List<LocalDate> list = new ArrayList<LocalDate>();
while (date.isBefore(end)) {
if (!holidays.contains(date)) {
list.add(date);
}
date = date.plusDays(1);
}
return Collections.unmodifiableList(list);
}
Answer to second question:
LocalDate date = LocalDate.now();
int dow = date.getDayOfWeek();
// dow has the values 1=Monday, 2=Tuesday, ..., 7=Sunday
UPDATE for question 2:
An alternative to using numbers (or named constants like DateTimeConstants.MONDAY which are finally only numbers, too) is to use the property dayOfWeek().getAsText(). It allows access to localized names like "Monday" (English) or "Lundi" (French).
See this code example:
LocalDate date = LocalDate.now();
String nameOfWeekday = date.dayOfWeek().getAsText(Locale.ENGLISH);
For such date-only problems the type LocalDate is by far the most simple and straight-forward one to use. The type DateTime only makes sense if you have a time part and a need for timezone calculations.
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