Matthew Cassar Matthew Cassar - 7 months ago 17
Java Question

Java Calendar Not Changing Values

I am writing an application to receive past stock data in java.
I am using a Calendar to chose the to and from dates when calculating a six day average however this is not working due to the to calendar being the same as the from despite subtracting days in the latter...

private BigDecimal calcMovingAvg(int days, Calendar start){

Calendar to = start;

int temp = Functions.weekdays(start.getTime(), days);
temp = temp - (2 * temp);

start.add(start.DAY_OF_MONTH, temp);

BigDecimal d = new BigDecimal(String.valueOf(days));

List<HistoricalQuote> histQuotes = null;
try {
//Calling a method to get stock history between start and to date
histQuotes = stk.getHistory(start, to, Interval.DAILY);
System.out.println(histQuotes);
} catch (IOException e) {
e.printStackTrace();
}


Start is already defined and working

I save to = start so as to have an end date when taking the previous 6 days for averaging

Functions.weekdays calculates how many of those 6 days were actually weekdays (business days) and adjusts the number accordingly (temp is the number of days needed to get 6 business days).

When comparing, I am getting start == to, why is start not changing?

Answer
    Calendar to = (Calendar) start.clone();

    int temp = Functions.weekdays(start.getTime(), days);
    temp = temp - (2 * temp);

    start.add(start.DAY_OF_MONTH, temp);

The calendar was using the same instance. Cloning the calendar solved the issue as it created two separate entities.