2

I want to calculate the start date of the last month. I have referred this post and I have written the snippet as follows:

Calendar calendar = getCalendar(new Date());
calendar.set(Calendar.DAY_OF_MONTH-1,
        calendar.getActualMinimum(DAY_OF_MONTH));
calendar = getTimeToBeginningOfDay(calendar);

return calendar.getTime();

With this I'm able to get the Date before the end of the last month. Help me get the start date of Any help would be appreciated.

Community
  • 1
  • 1
Venkat
  • 2,604
  • 6
  • 26
  • 36
  • Your subtracting 1 from the constant int field DAY_OF_MONTH? So what field of the calendar is being set? Also, correct me if I'm wrong but isn't the start date of each month the first day of the month? Just set the calendar object's DAY_OF_MONTH field to 1. `calendar.set(Calendar.DAY_OF_MONTH, 1);` Of course you want to roll it back a month. `calendar.add(Calendar.MONTH, -1);` – km1 Sep 13 '12 at 02:09

3 Answers3

1

You may get what you expect with :

Calendar c = Calendar.getInstance();

// substract one month
c.add(Calendar.MONTH, -1);

// get to the lowest day of that month
c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));

// lowest possible time in that day
c.set(Calendar.HOUR_OF_DAY, c.getActualMinimum(Calendar.HOUR_OF_DAY));
c.set(Calendar.MINUTE, c.getActualMinimum(Calendar.MINUTE));
c.set(Calendar.SECOND, c.getActualMinimum(Calendar.SECOND));
Frederik.L
  • 5,522
  • 2
  • 29
  • 41
1

You should never do math on field constants such as Calendar.DAY_OF_MONTH. What you want to do is:

Calendar calendar = getCalendar(new Date());
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar = getTimeToBeginningOfDay(calendar);

return calendar.getTime();
epsalon
  • 2,294
  • 12
  • 19
1

If you just want the first day of the previous month, then this should do it.

    Calendar instance = Calendar.getInstance();
    instance.add(Calendar.MONTH, -1);
    instance.set(Calendar.DAY_OF_MONTH, 1);

    System.out.println(instance.getTime());

If you need to to clear out the time component, then use getTimeToBeginningOfDay() mentioned in the post to achieve this.

IceMan
  • 1,398
  • 16
  • 35