tags:

views:

93

answers:

3
+1  Q: 

calendar methods

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??

+3  A: 

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); 
}
oxbow_lakes
+1  A: 

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

Lazy Bob
+2  A: 

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

Jon Skeet
Not much point in learning Joda time now that JSR 310 is about to hit the shelves?
oxbow_lakes
I'll believe it when I see it actually released - and when everyone is actually *using* Java 7. I don't expect everywhere to jump to it the instant it's shipped. Besides with the same designer I expect it'll be similar enough that time spent learning Joda Time now won't be wasted anyway.
Jon Skeet
If you look at it, it feels quite different to JODA
oxbow_lakes
I bet it feels closer to Joda than it does to Date/Calendar... and anyway, in the meantime I'd *much* rather use a decent API with an appropriate separation of dates, times, instants etc than calendar. I've been doing a *lot* of date/time work over the last year, and I wouldn't go back to Date/Calendar for anything...
Jon Skeet