Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda-Time: How to get the day from a particular date in a year? [closed]

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.

like image 826
Solace Avatar asked Dec 16 '25 15:12

Solace


1 Answers

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.

like image 162
Meno Hochschild Avatar answered Dec 19 '25 05:12

Meno Hochschild