1

Maybe there is a smarter way of resolving my issue so my question might not be pointing you into the right direction of thinking.

However, my issue is that I want to initialize my Calendar instance only once at the beginning of the program, so I work with only that date and time.

Then I want to pass that calendar to a method which adds/subtracts some months/days from it and uses that datetime for an API call. The thing is, I want to reuse the initial date all over in different places of my application, but that method keeps changing my Calendar instance.

CODE:

Initialization of the Calendar on the beginning of the main thread:

Calendar cal = Calendar.getInstance();

Method using the instance:

private static String getDateUntil(int i, Calendar cal) {
    int month = 0 - i;
    //Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, month);
    Date result = cal.getTime();
    String dateUntil = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss").format(result);

    return dateUntil;
}

After calling this method, my cal is changed and I can't reuse the initial datetime. Any ideas?

Nayuki
  • 17,911
  • 6
  • 53
  • 80
Ondrej Tokar
  • 4,898
  • 8
  • 53
  • 103

2 Answers2

3

Use clone in your methods:

private static String getDateUntil(int i, Calendar cal) {
    int month = 0 - i;
    Calendar mycal = (Calendar)cal.clone();  // Make a copy of the initial instance
    mycal.add(Calendar.MONTH, month);
    Date result = mycal.getTime();
    String dateUntil = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss").format(result);
    return dateUntil;
}
Nayuki
  • 17,911
  • 6
  • 53
  • 80
1

Use calendar.clone() to obtain a copy.

Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51