Get the first Monday of a month
java
Solution
`getFirstDayOfWeek()` returns which day is used as the start for the current locale. Some people consider the first day Monday, others Sunday, etc.
This looks like you'll have to just set it for `DAY_OF_WEEK = MONDAY` and `DAY_OF_WEEK_IN_MONTH = 1` as that'll give you the first Monday of the month. To do the same for the year, first set the `MONTH` value to `JANUARY` then repeat the above.
Example:
private static Calendar cacheCalendar;
public static int getFirstMonday(int year, int month) {
cacheCalendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cacheCalendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
cacheCalendar.set(Calendar.MONTH, month);
cacheCalendar.set(Calendar.YEAR, year);
return cacheCalendar.get(Calendar.DATE);
}
public static int getFirstMonday(int year) {
return getFirstMonday(year, Calendar.JANUARY);
}
Here's a simple JUnit that tests it: http://pastebin.com/YpFUkjQG
Problem
I want to get the day on which the first Monday of a specific month/year will be. What I have: I basically have two int variables, one representing the year and one representing the month. What I want to have: I want to know the first Monday in this month, preferably as an int or Integer value. For example: I have 2014 and 1 (January), the first Monday in this month was the 6th, so I want to return 6. Problems: I thought I could do that with the `Calendar` but I am already having trouble setting up the calendar with only Year and Month available. Furthermore, I'm not sure how to actually return the first Monday of the month/year with `Calendar`. I already tried this: ``` Calendar cal = Calendar.getInstance(); cal.set(this.getYear(),getMonth(), 1); int montag = cal.getFirstDayOfWeek(); for( int j = 0; j < 7; j++ ) { int calc = j - montag; if( calc < 0 ) { calc += 6; } weekDays[calc].setText(getDayString(calc)); } ```