简体   繁体   中英

Get the first day of a month in java FOR a local calendar

I know how to do it for the standard Gregorian calendar but I want it for 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, let me know if this is the correct procedure for a calendar app. I'll appreciate if you can suggest any techniques.

If you need more details about my calendar please message and I'll provide full details.

I guess parameters M, D and Y are for month, day, year. I also guess you are talking about getting the weekday of the first day of month, right?

I would use the builtin functionality for calendars using the Calendar class from Java SE .

This might look like:

...
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));
...

You might set additional fields first before, depending on what your needs are of course.

Edit (regarding the custom type of your calendar):

You might declare constant arrays with the lengths of the months if there aren't any leap years in your calendar. Then you could manually add up your week days using the modulo operator, like about so:

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 hint:

This only works if there aren't any leap years in your calendar system!

Edit:

Replaced sample number for year length and ellipsis for month length with real numbers

Edit:

Added constant for first day in first year (1/1/0).

This is a good method and is based on Zeller's congruence which you can see for further explanation. However I would go with Java's standard Calendar methods as @olik79 has posted here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM