Sol*_*ace 3 java datetime calendar date jodatime
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.
回答第一个问题:
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);
}
Run Code Online (Sandbox Code Playgroud)
回答第二个问题:
LocalDate date = LocalDate.now();
int dow = date.getDayOfWeek();
// dow has the values 1=Monday, 2=Tuesday, ..., 7=Sunday
Run Code Online (Sandbox Code Playgroud)
问题2的更新:
使用数字(或命名常量,如DateTimeConstants.MONDAY,最后也只是数字)的替代方法是使用属性dayOfWeek().getAsText().它允许访问本地化名称,如"Monday"(英语)或"Lundi"(法语).
看到这个代码示例:
LocalDate date = LocalDate.now();
String nameOfWeekday = date.dayOfWeek().getAsText(Locale.ENGLISH);
Run Code Online (Sandbox Code Playgroud)
对于此类仅限日期的问题,该类型LocalDate是迄今为止最简单和直接使用的类型.DateTime如果您有时间部分并且需要时区计算,那么这种类型才有意义.