Nitish
Nitish

Reputation: 856

generating calendar with given month and year

How to generate the Calendar when month and year are the input parameters?

Note: I have already calculated the number of days a month contains.

Upvotes: 0

Views: 1250

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 339332

Using java.time

The modern way is with the java.time classes that supplant the troublesome old legacy Calendar & Date classes.

YearMonth

The YearMonth class represents, well, a year and a month, without any date or time-of-day or time zone.

YearMonth ym = YearMonth.of( 2017 , Month.MARCH );

LocalDate

You can generate a LocalDate from that.

LocalDate firstOfMonth = ym.atDay( 1 );
LocalDate endOfMonth = ym.atEndOfMonth();

If you want the dates in between, loop. Increment the date by one day at a time. Check to see if each day is still in the same YearMonth. If not, you have incremented too far and can stop.

List<LocalDate> dates = new ArrayList<>( 31 );
LocalDate localDate = ym.atDay( 1 );
while ( YearMonth.from( localDate ).equals( ym ) {
    dates.add( localDate );
    // Set up the next loop.
    localDate = localDate.plusDays( 1 );
}

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Upvotes: 0

Bozho
Bozho

Reputation: 597224

Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, month); // 0-based
c.set(Calendar.YEAR, year);

Of course, I should suggest using joda-time DateTime instead of Calendar for date-time operations.

Upvotes: 2

Michael
Michael

Reputation: 6499

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Calendar.MAY); // note this is a 0-11 value for jan-dec
calendar.set(Calendar.DATE, 20); // pick the 20th day...or whatever from input

Note that doing it this way will automatically recalculate the rest of the fields (such as how many days are in the month, etc). You can also use the add() function on Calendar to add days and it'll take all of that into account as well.

See also: http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html

Upvotes: 0

flash
flash

Reputation: 6820

Why not like this?

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);

Upvotes: 2

Related Questions