Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 421
waldemar Avatar asked Jan 27 '15 14:01

waldemar


2 Answers

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

like image 112
Pham Trung Avatar answered Nov 13 '22 11:11

Pham Trung


Java Date has very poor API. Instead of this I would recommend you to use Joda Time.

In Joda it would look like this:

LocalDate endOfMonth = date.dayOfMonth().withMaximumValue();
like image 29
MAGx2 Avatar answered Nov 13 '22 11:11

MAGx2