Determine which day of the week is each date of the month

I want to create a calendar with Java 8. For now, 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 (e.g. May).

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

+5
source share
2 answers

You have a YearMonth object. For each day of the month, you can call atDay(dayOfMonth) to return LocalDate on that particular day of the month. Using LocalDate you can call:

Thus, you must modify your Dayes list to hold LocalDate instead of Integer s, 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())); 

It will print every day of this month, followed by the corresponding day of the week.

As a note, you can get the actual display value for the day of the week (instead of the name() listing, as mentioned above) by calling getDisplayName(style, locale) . The style describes how to write days (long form, short form ...), and the locale is the language used for the display name. An example is:

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

which will display the full text of the day of the week in English. Output example on 04/2016 with the above change:

 1 Friday 2 Saturday 3 Sunday 4 Monday 5 Tuesday 
+6
source

It may be a bit of a “hack” solution, but if you are trying to create a calendar for any year, you may have to use the “date of binding” (for example, January 1, 1800 on Wednesday). Then you can calculate the number of days that occurred between January 1, 1800 and your current year / month / day. After you figure out how many days have passed using Modular 7, you can determine what day it is, and then fill out the calendar for this month.

0
source

All Articles