-
Calendar Date Range
Hi All,
I am trying to get the last month date range (1st to end of month). I have following code:
Code:
public static void main(String[] args) {
Calendar todaysDate = Calendar.getInstance();
Integer month = todaysDate.get(Calendar.MONTH);
Integer days = todaysDate.get(Calendar.DAY_OF_MONTH);
Integer year = todaysDate.get(Calendar.YEAR);
if (month == 0) {
year--;
month = 12;
}
Calendar lastMonthDate = Calendar.getInstance();
lastMonthDate.set(year, month, 15); //set 15 to simplyfy 30/31 check.
Integer lastDay = lastMonthDate.getMaximum(Calendar.DAY_OF_MONTH);
Calendar startDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
startDate.set(year, month, 1);
endDate.set(year, month, lastDay);
System.out.println("Date Range : " + startDate.get(Calendar.MONTH)
+ "-"
+ startDate.get(Calendar.DATE)
+ "-"
+ startDate.get(Calendar.YEAR)
+ " to "
+ endDate.get(Calendar.MONTH)
+ "-"
+ endDate.get(Calendar.DATE)
+ "-"
+ endDate.get(Calendar.YEAR));
}
I am expecting to get print result as
Date Range : 10-1-2012 to 10-31-2012
but I am getting
Date Range : 10-1-2012 to 11-1-2012
What I am doing wrong?
-
Re: Calendar Date Range
your expectation is already wrong!
the month is 0 based, so october is 9 and not 10 ! (Calendar (Java Platform SE 6))
and so you have to use
startDate.set(year, month-1, 1);
endDate.set(year, month-1, lastDay);
and
(startDate.get(Calendar.MONTH)+1)
(endDate.get(Calendar.MONTH)+1)
-
Re: Calendar Date Range
Or just use the constants that come with Calendar.
That's what they're there for.