javacalendarjava-6

Wrong last day of month


Where is some function to get the last day of month in my service?

 DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        Date date = format.parse(stringDate);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.DATE, -1);

        Date lastDayOfMonth = calendar.getTime();

        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        return sdf.format(lastDayOfMonth);

So, this method correctly works elsewhere, but in US last day is always 29 (last day - 1)

stringDate is date in format "yyyy-MM-dd"


Solution

  • I believe this problem is due to Day Light saving time in US.

    You can change this by setting the Timezone for Calendar to different timezone.

    Related question: Adding days with java.util.Calendar gives strange results