apart from the inbuilt functions, can we use any simple formulas to calculate the start day of the month given month and year as inputs??
Yes - use the Calendar
object:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2009)
cal.set(Calendar.MONTH, Calendar.JUNE) //0-based so that Calendar.JANUARY is 0
cal.set(Calendar.DAY_OF_MONTH, 1)
Then:
cal.get(Calendar.DAY_OF_WEEK); //is Calendar.MONDAY
So you could easily compose a method for this:
/** takes a 1-based month so that Jjanuary is 1 */
public int getDayAtStart(int year, int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
return cal.get(Calendar.DAY_OF_WEEK);
}
construct a calendar (cal) with the given month and year, and day 1, and cal.get(Calendar.DAY_OF_WEEK)
... sorry, don't think there are any builtins just for that task
As ever, I'd recommend using Joda Time. I dare say java.util.Calendar
will work for this, but I prefer to use Joda Time for all date and time calculations wherever possible. The built-in APIs are horrible. Joda makes this very easy indeed. (Unless specified, LocalDate
assumes an ISOChronology
- I expect that's what you want, but you can specify a different one if you need to.)
import org.joda.time.*;
public class Test
{
// Just for the sake of a simple test program!
public static void main(String[] args) throws Exception
{
// Prints 1 (Monday)
System.out.println(getFirstDayOfMonth(2009, 6));
}
/** Returns 1 (Monday) to 7 (Sunday) */
private static int getFirstDayOfMonth(int year, int month)
{
LocalDate date = new LocalDate(year, month, 1);
return date.getDayOfWeek();
}
}
Or if you just need to do this in one place, you can mash it into a single line if you want:
int day = new LocalDate(year, month, 1).getDayOfWeek();
It's hard to see how it could be much simpler than that :)