Reputation: 953
I am creating programm that uses this class to retrieve current date. In order to work with that I need to get back some time in past. For example, today is 3.11.2013 user selects 18 month period, so I am using this code:
Calendar ca =Calendar.getInstance();
ca.add(Calendar.MONTH, -n);
Where the n variable stands for user input (months). Works great. But now I want to retrieve each month and show that on screen like this:
September,2012
October,2012
.....
.....
November, 2013
I tried to create loop, but I can't understand how I can realy make for each loop run add 1 month to start date. Update:
int i =0;
Calendar ca =Calendar.getInstance();//iegūstam pašreizējo laiku
ca.add(Calendar.MONTH, -n);
ca.set(Calendar.DAY_OF_MONTH, 1);
while (i<n)
{
int month_n = ca.get(Calendar.MONTH);
int year_n = ca.get(Calendar.YEAR);
try {//iegūstam datus ko rakstīt failā
//record.setDate(5);//uzstādam vērtības
record.setIncome(input.nextDouble());
record.setAtv(atv_sum);
record.setSumAtv(atv_sum+45.00);
double iedz=(((record.getIncome()-record.getSumAtv())/100)*24);//iedz ienakuma nodoklis
double soc_apd=(((record.getIncome()-record.getSumAtv())/100)*11);//sociālās apdr.nodoklis
double netto =record.getIncome()-(iedz+soc_apd);
if(record.getIncome()>0){
output.format("%-10s%-20s%-20s%-20s%-20s%-20s%-20s%-20s\n",
year_n,
month_n,
record.getIncome(),
record.getAtv(),
record.getSumAtv(),
iedz,soc_apd,netto);//null pointer exception
}
else
{
System.out.println("Kļūda alga ievadīta zem 0");
input.nextLine();
}
}
catch ( FormatterClosedException formatterClosedException ){
System.err.println("Kļūda rakstot failā");
return;
}
catch (NoSuchElementException elementException){
System.err.println("Nepareizs ievads. Mēģiniet vēlreiz");
input.nextLine();
}
// System.out.printf("%s \n", "Ievadiet mēneša ienākumus ");
ca.add(Calendar.MONTH, 1);
i++;
}
Thanks :)
Upvotes: 0
Views: 67
Reputation: 691715
Calendar ca = Calendar.getInstance(); // this is NOW
// set the date to the first of the month, to avoid surprises if the current date is 31.
ca.set(Calendar.DAY_OF_MONTH, 1);
// go n months before the first of this month
ca.add(Calendar.MONTH, -n);
for (int i = 0; i < n; i++) {
// todo: format the date as you want and print it. See SimpleDateFormat
// go to the next month
ca.add(Calendar.MONTH, 1);
}
Upvotes: 2