views:

378

answers:

3

I want to select records that have a created date between the first and the last day of a given month. I calculate the month with begin and enddate the following way:

The Date "month" is just a random date inside the timeframe

Calendar cal = Calendar.getInstance();
cal.setTime(month);
int endday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int actualmonth = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);

Date begin = format.parse("01." + actualmonth + "." + year);
Date end = format.parse(endday + "." + actualmonth + "." + year);

When I think about this, I'd actually have to set the daytime as well, to avoid records going missing on the last day of the month.

I feel this is kinda inelegant, anyone up for a better solution?

+2  A: 

What I would do is create a Calendar and set the month and year to the month you want, the day to 1, hour, minute and millisecond to zero. Then take the date of that for your begin range. Then I'd add a month, and then subtract a millisecond. Take the date of that for your end range.

  Calendar dateCal = Calendar.getInstance();
  dateCal.set(Calendar.MONTH, month);
  dateCal.set(Calendar.YEAR, year);
  dateCal.set(Calendar.HOUR_OF_DAY, 0);
  dateCal.set(Calendar.MINUTE, 0);
  dateCal.set(Calendar.SECOND, 0);
  dateCal.set(Calendar.MILLISECOND, 0);
  Date startDate = dateCal.getTime();

  dateCal.add(Calendar.MONTH, 1)
  dateCal.add(Calendar.MILLISECOND, -1);
  Date endDate = dateCal.getTime();
Paul Tomblin
+2  A: 

There are methods available in the Calendar class for getting the first and last days of the month:

getActualMaximum(Calendar.DAY_OF_MONTH)
getActualMinimum(Calendar.DAY_OF_MONTH)
James
A: 

okay, solved it by Paul's example:

Calendar cal = Calendar.getInstance();
cal.setTime(month);
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.getActualMinimum(Calendar.DATE), 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date begin = cal.getTime();
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.MILLISECOND, -1);
Date end = cal.getTime();

thanks everyone

Stefan Ernst