Get the first day of the month of the local calendar in Java
I
know how to do this for the standard Gregorian calendar, but I want to use a local calendar for my community. The plan is to make a calendar app for Android.
I have this code for the Gregorian calendar but can’t figure out the algorithm behind it.
public static int day(int M, int D, int Y) {
int y = Y - (14 - M) / 12;
int x = y + y/4 - y/100 + y/400;
int m = M + 12 * ((14 - M) / 12) - 2;
int d = (D + x + (31*m)/12) % 7;
return d;
}
Also, please tell me if this is the right step for the calendar app. I would appreciate any technical suggestions you could make.
If you need more details about my calendar, leave a message and I will provide full details.
Solution
I guess the parameters M, D, and Y represent month, day, year. I’m also guessing you’re talking about getting the first working day of each month, right?
I’ll use the built-in calendar feature from the Calendar class of Java SE
This might look like this:
...
Calendar localCalendar = Calendar.getInstance();
localCalendar.set(Calendar.MONTH, Calendar.AUGUST);
localCalendar.set(Calendar.DAY_OF_MONTH, 1);
int dayOfWeek = localCalendar.get(Calendar.get(DAY_OF_WEEK));
...
Of course, you can set other fields first, depending on your needs.
Edit (about custom types for calendars):
If you don’t have leap years in your calendar, you can declare a constant array with the length of the month. You can then manually add your workdays using the modulo operator as follows:
int WEEKDAY_OF_FIRST_DAY_IN_FIRST_YEAR = 3; 0 for monday, 1 for tuesday, etc.
int LENGTH_OF_WEEK = 7;
int DAYS_IN_YEAR = 365; 31 + 32 + 31 + 32 + 31 + 30 + 30 + 30 + 29 + 29 + 30 + 30
int DAYS_OF_MONTHS[] = { 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30 };
public static int day(int M, int D, int Y) {
int firstDayInCurrentYear = WEEKDAY_OF_FIRST_DAY_IN_FIRST_YEAR +
(Y * DAYS_IN_YEAR) % LENGTH_OF_WEEK;
int firstDayOfMonth = firstDayInCurrentYear;
for (int month = 0; month < M; month++) {
firstDayOfMonth =
(firstDayOfMonth + DAYS_OF_MONTH[month]) % LENGTH_OF_WEEK;
}
return firstDayOfMonth;
}
Additional tips:
This only applies if there are no leap years in the calendar system!
Edit:
Replace the number
of samples for the year length and the ellipsis for the month length with a real number
Edit:
Added a constant for the first day of the first year (1/1/0).