Reputation: 343
I have a strange problem when i increment days in Calendar. I want to loop over every day of a year. This is my code
Date d = null;
SimpleDateFormat textFormat = new SimpleDateFormat("dd-MM-yyyy");
String paramDateAsString = "10-1-2012";
d = textFormat.parse(paramDateAsString);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
for(int i = 0; i < 365; i++) {
cal.add(Calendar.DAY_OF_YEAR, 1);
System.out.println(cal.get(Calendar.YEAR)+"-"+cal.get(Calendar.MONTH)+1+"- "+cal.get(Calendar.DAY_OF_MONTH)+" 00:00:00'");
}
I get this output:
...
2012-01-29 00:00:00'
2012-01-30 00:00:00'
2012-01-31 00:00:00'
2012-11-1 00:00:00'
2012-11-2 00:00:00'
...
Upvotes: 0
Views: 134
Reputation: 1500504
This is the problem:
"-"+cal.get(Calendar.MONTH)+1
That's actually performing string concatenation - it's effectively
("-" + cal.get(Calendar.MONTH)) + 1
So when cal.get(Calendar.MONTH)
returns 1, that's effectively:
("-" + 1) + 1 // which is...
"-1" + 1 // which is...
"-11"
You could just bracket the addition:
"-" + (cal.get(Calendar.MONTH) + 1)
... but it would be better to use SimpleDateFormat
to perform the formatting instead of doing it manually.
Upvotes: 2