Reputation: 7520
I am creating a simple program that allows the user to see how many days between the months they set.
For example From January - March
I can get the current day of the month using this:
Calendar.DAY_OF_MONTH
What I want is how can I supply a value in the month?
I have this simple code:
public static void machineProblemTwo(int startMonth, int endMonth) {
int[] month = new int[0];
int date = 2015;
for(int x = startMonth; x <= endMonth; x++) {
System.out.println(x + " : " + getMaxDaysInMonth(x,date));
}
}
public static int getMaxDaysInMonth(int month, int year){
Calendar cal = Calendar.getInstance();
int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // how can I supply the month here?
return days;
}
How can i do that? Can you help me with this?
Upvotes: 4
Views: 11091
Reputation: 2095
We can do this as well:
private DateTime getNewDate(DateTime date, int dayOfMonth) {
// first we need to make it 1st day of the month
DateTime newDateTime = new DateTime(date.getYear(), date.getMonthOfYear(), 1, 0, 0);
int maximumValueOfDays = newDateTime.dayOfMonth().getMaximumValue();
// to handle the month which has less than 31 days
if (dayOfMonth > maximumValueOfDays) {
newDateTime = newDateTime.dayOfMonth().withMaximumValue();
} else {
newDateTime = newDateTime.withDayOfMonth(dayOfMonth);
}
return newDateTime;
}
Upvotes: 0
Reputation: 1500525
You need to set the calendar to be in that year and month before asking for the maximum value, e.g. with
cal.set(year, month, 1);
(Or with the calendar constructor as per David's answer.)
So:
public static int getMaxDaysInMonth(int month, int year) {
Calendar cal = Calendar.getInstance();
// Note: 0-based months
cal.set(year, month, 1);
return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
Alternatively - and preferrably - use Joda Time or Java 8:
// Java 8: 1-based months
return new LocalDate(year, month, 1).lengthOfMonth();
// Joda Time: 1-based months
return new LocalDate(year, month, 1).dayOfMonth().getMaximumValue();
(I'm sure there must be a simpler option for Joda Time, but I haven't found it yet...)
Upvotes: 8
Reputation: 79838
Use the constructor for GregorianCalendar
where you pass the year, month and day. Don't forget that the months go from 0 to 11 (0 for January, 11 for December).
public static int numberOfDaysInMonth(int month, int year) {
Calendar monthStart = new GregorianCalendar(year, month, 1);
return monthStart.getActualMaximum(Calendar.DAY_OF_MONTH);
}
Upvotes: 6