Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine which day of week is each date of the month

I want to create a calendar with Java 8. So far I have this:

YearMonth yearMonthObject = YearMonth.of(year, month);
int daysOfCurrentMonth = yearMonthObject.lengthOfMonth();

int i = 1;
ArrayList<Integer> Dayes = new ArrayList<Integer>();
for(i=1; i<=daysOfCurrentMonth; i++){
    Dayes.add(i);
}

Dayes.forEach(value -> System.out.print(value));

which prints the days of the current month (for example May).

How can I determine that 1 is Sunday, 2 is Monday, 3 is Tuesday, ..., 8 is Sunday (next week), etc.?

like image 720
dios231 Avatar asked May 11 '16 18:05

dios231


Video Answer


1 Answers

You have a YearMonth object. For each day of the month, you can call atDay(dayOfMonth) to return a LocalDate at that specific day of month. With that LocalDate, you can then call:

  • getDayOfMonth() to get back the day of the month as an int;
  • getDayOfWeek() to get the day of the week as a DayOfWeek. This is an enumeration of all the days of the week.

As such, you should change your Dayes list to hold LocalDates instead of Integers, and then you can have, for example:

YearMonth yearMonthObject = YearMonth.of(year, month);
int daysOfCurrentMonth = yearMonthObject.lengthOfMonth();

ArrayList<LocalDate> dayes = new ArrayList<LocalDate>();
for(int i = 1; i <= daysOfCurrentMonth; i++){
    dayes.add(yearMonthObject.atDay(i));
}

dayes.forEach(value -> System.out.println(value.getDayOfMonth() + " " + value.getDayOfWeek()));

This will print each day of that month followed by the corresponding day of the week.

As a side-note, you can get a real display value for the day of week (instead of the name() of the enum like above) by calling getDisplayName(style, locale). The style represents how to write the days (long form, short form...) and the locale is the locale to use for the display name. An example would be:

value.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH)

which would output the full text of the day of the week in English. Sample output for 04/2016 with the above change:

1 Friday
2 Saturday
3 Sunday
4 Monday
5 Tuesday
like image 182
Tunaki Avatar answered Sep 30 '22 17:09

Tunaki