Steve Chambers Steve Chambers - 2 months ago 20
Java Question

How to assign Calendar.add() result to a new Calendar object (in Java 7)?

I want to add a month to a date...

But I want to assign the result to a new variable without changing the original date.
I'd like to do this the standard way, which seems to be using Calendar.add() but that method changes the Calendar object used for calculation.

So I'm wondering what the "proper" thing to do here is - should I use Object.clone() and cast back to Calendar? Instinctively this seems a bit horrible and wrong. Alternatively should I create a new Calendar object from the original one using a syntax like:

Calendar newCalendar = Calendar.getInstance();

Seems pretty horrible too... surely there must be an easier way - please somebody tell me I'm missing something!

(...but please don't tell me to use Joda Time or Java 8 - I can't due to project constraints.)


Calendar is not a pretty library so you shouldn't expect it to be.

AFAIK, Java 8 will have a new Date/Time library based on JodaTime. ;)

please don't tell me to use Joda Time - I can't due to project constraints

In that case, just learn to enjoy using Calendar and its quirks.