Reputation: 562
how to get minimum and maximum date from given month in java using java.util.Calendar.
Upvotes: 3
Views: 15775
Reputation: 1964
For people that are looking for solution using Java 8 API:
Given month min date:
YearMonth.from(clock.instant().atZone(ZoneId.of("UTC")))
.atDay(1)
.atStartOfDay()
.toInstant(ZoneOffset.UTC)
Given month max date:
YearMonth.from(clock.instant().atZone(ZoneId.of("UTC")))
.atEndOfMonth()
.atTime(LocalTime.MAX)
.toInstant(ZoneOffset.UTC)
Upvotes: 0
Reputation: 562
I got solution as below,
public void ddl_month_valueChange(ValueChangeEvent event) {
int v_month = Integer.parseInt(event.getNewValue().toString()) - 1;
java.util.Calendar c1 = java.util.Calendar.getInstance();
c1.set(2011, v_month, 1);
Date d_set_att_from = c1.getTime();
cal_att_from_date.setValue(d_set_att_from);
c1.add(java.util.Calendar.MONTH, 1);
c1.add(java.util.Calendar.DATE, -1);
Date d_set_att_to = c1.getTime();
cal_att_to_date.setValue(d_set_att_to); }
Upvotes: 0
Reputation: 3024
Minimum date is always 1 and Maximum date can be calculate as
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
int year = 2010;
int month = Calendar.FEBRUARY;
int date = 1;
int maxDay =0;
calendar.set(year, month, date);
System.out.println("First Day: " + formatter.format(calendar.getTime()));
//Getting Maximum day for Given Month
maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(year, month, maxDay);
System.out.println("Last Day: " + formatter.format(calendar.getTime()));
Hopefully this will helps
Upvotes: 1
Reputation: 2941
This could be done this way:
c = ... // get calendar for month you're interested in
int numberOfDays = c.getActualMaximum(Calendar.DAY_OF_MONTH)
You could find minimum and maximum value the same way for any of components of the date.
Upvotes: 3
Reputation: 800
Have you tried the following?
After setting your calendar object to your desired month,
calendar.getActualMaximum(Calendar.DATE);
For the minimum, I suppose it's always the first.
Hope that helps.
Upvotes: 1
Reputation: 68962
The minimum is always the 1st of this month. The maximum can be determined by adding 1 to month and subtracting 1 from the Calendar day field.
Upvotes: 5