views:

163

answers:

2

Hello, I'm trying to create a date range to cover a full month, i.e.

[startDate; endDate]

As such, I have a reference date and try to create a new date from it. I'm having problem with the "endDate" because I want it to be near the end of the day (i.e. 23:59:59).

The code I'm using is the following:

  public static Date previousMonthLastDate(Date referenceDate) {
    Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    calendar.setTime(referenceDate);
    calendar.add(Calendar.MONTH, -1); // move to the previous month
    int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    calendar.set(Calendar.DAY_OF_MONTH, lastDay);
    // set the time to be the end of the day
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);

    return calendar.getTime();
  }

This code is working as expected on the Android emulator. However, running it on a real phone gives the wrong date. As such, I'm assuming it is some kind of timezone problem.

On the phone, instead of giving say 31/August/2010, it gives 01/September/2010. This value seams to be set after the line of code that sets the HOUR_OF_DAY to 23.

Any ideas?

Thanks.

+2  A: 

If you want the timezone to depend on the phone settings, you shouldn't force a timezone when creating your calendar. Just use:

Calendar calendar = Calendar.getInstance();
Damien
+3  A: 

I can't answer why it's happening, but have you tried setting it to the first day of the next month and subtracting one second/millisecond?

calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.add(Calendar.MILLISECOND, -1);
waxwing
Either that or simply use an inequality (i.e. before the first day of the next month) in any calculations. That way you don't get confused by leap seconds or clock-change days... Of course, if you are only displaying the value, and not using it in any calculations, then the answer here is good.
Bill Michell