Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Customize adding 1 month to the current date

Tags:

java

date

I've read around and basically I've figured out that the Calendar object is capable of adding 1 month to a date specified by using something like:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);

Although I don't like its behavior whenever the date is on either the 30 or 31. If ever I add 1 month to 01/31/2012, the output becomes 02/29/2012. When I add 1 more month, it becomes 03/29/2012.

Is there anyway I can force 02/29/2012 to become 03/01/2012 automatically?

Basically this is what I want to happen:

Default date: 01/31/2012

Add 1 month: 03/01/2012

Add 1 more month: 03/31/2012

like image 441
mpmp Avatar asked Sep 25 '26 22:09

mpmp


1 Answers

What you are asking for is some implicit knowledge that if the starting date is the last day of the month, and you add 1 month, the result should be the last day of the following month. I.e. the property "last-day-of-month" should be sticky.

This is not directly available in Java's Calendar, but one possible solution is to use Calendar.getActualMaximum(Calendar.DAY_OF_MONTH) to reset the day after incrementing the month.

Calendar cal = ...;
cal.add(Calendar.MONTH,1);
cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DAY_OF_MONTH));

You could even subclass GregorianCalendar and add a method

public Calendar endOfNextMonth() { ... }

to encapsulate the operation.

like image 92
Jim Garrison Avatar answered Sep 27 '26 13:09

Jim Garrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!