Reputation: 15734
Here is my code:
Month is passed in on a loop. First 0 (since it is January as I type), then 1, and so on. Next month when it is February, this loop will start from that date. 1, 2, etc.
int thisMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
cal = Calendar.getInstance();
df = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
cal.set(Calendar.MONTH, month + thisMonth);
String sMonth = df.format(cal.getTime());
In the first loop, sMonth
is March 2015.
In the second loop, sMonth
is March 2015.
In the third loop, sMonth
is April 2015.
In the fourth loop, sMonth
is May 2015.
..and so on
As you see, the first month is NOT February as expected. I believe it is January 29th so that may have some cause as we are so close to February. But if that is the case, why would this happen twice?
I know since I am not working with unix timestamps things aren't exact, is there away to calculate this where I can at least get accurate month ordering?
Upvotes: 1
Views: 164
Reputation: 338594
Use only java.time classes.
YearMonth
.now( ZoneId.of ( "Asia/Tokyo" ) )
.plusMonths ( 1 )
In modern Java, use java.time classes. Never use the legacy classes Calendar
, Date
, etc.
First 0 (since it is January as I type
In contrast to the legacy classes, the java.time classes use sane numbering. So months are 1-12 for January-December.
this loop will start from that date
You do not actually show your "loop" code. So I can only guess. You seem to be interested in just the particular month, not the date. We have a class for that YearMonth
.
To get the current month requires a time zone. For any given moment the time and the date vary around the globe by time zone. That means the month too may vary when the date is the first/last of the month.
ZoneId z = ZoneId.of ( "America/Edmonton" ) ;
YearMonth currentMonth = YearMonth.now( z ) ;
To go forward in time, add a month.
YearMonth nextMonth = currentMonth.plusMonths ( 1 ) ;
Upvotes: 1
Reputation: 58868
Since today is the 30th, you're getting the current date (2015-01-30), and incrementing the month to get 2015-02-30 - which "rolls over" to 2015-03-02 since February doesn't have 30 days.
One way to avoid this problem is to set the day-of-month to 1 before changing the month.
Upvotes: 1