# two given year-month

How do I find in-between year month between two given  year-month ?

Example:

Input:
2014-08  ,  2015-02

Output:
2014-09
2014-10
2014-11
2014-12
2015-01

Could you please suggest a simple and easy solution to this ?
JavaJava EEJSP

Last Comment
CEHJ

8/22/2022 - Mon
dpearson

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
mccarl

And if you are using (or can use) Java 8 you can do it quite easily...

import java.time.YearMonth;

public class TestYearMonth {
public static void main(String[] args) {
YearMonth start = YearMonth.parse("2014-08");
YearMonth end = YearMonth.parse("2015-02");

YearMonth ym = start.plusMonths(1);
while (ym.isBefore(end)) {
System.out.println(ym);
ym = ym.plusMonths(1);
}
}
}
cofactor

I am using java 6
mccarl

That's a shame, because you can probably see how much easier it is.

Anyway, Doug's solution should work fine for Java 6.

Otherwise, a solution out of left field, if all you have to do is generate those year month strings (ie. you don't need to do further arithmetic), you can with some simple String manipulation, such as...

public class TestYearMonth {
public static void main(String[] args) {
int start = parse("2014-08");
int end = parse("2015-02");

for (int i = start + 1; i < end; i++) {
System.out.println(String.format("%04d-%02d", i / 12, i % 12 + 1));
}
}

private static int parse(String string) {
return Integer.valueOf(string.substring(0, 4)) * 12 + Integer.valueOf(string.substring(5)) - 1;
}
}
CEHJ

You only need one Calendar doing it like that:

private void dumpMonths(String start, String end)
throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
Date startDate = format.parse(start);
Date endDate = format.parse(end);

Calendar cal = Calendar.getInstance();
cal.setTime(startDate);

Date date = startDate;

while (true) {
date = cal.getTime();

if (date.equals(endDate)) {
break;
}

System.out.println(format.format(date));
}
}
cofactor