문제

I have a list of holidays in a year. I need the following things.

  1. 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

  2. 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top