回答編集履歴
3
重大なミス
test
CHANGED
@@ -6,7 +6,7 @@
|
|
6
6
|
|
7
7
|
DateFormat format = new SimpleDateFormat("yyyyMM");
|
8
8
|
|
9
|
-
String now = format.format(calendar);
|
9
|
+
String now = format.format(calendar.getTime());
|
10
10
|
|
11
11
|
```
|
12
12
|
|
2
スペルミス
test
CHANGED
@@ -56,7 +56,7 @@
|
|
56
56
|
|
57
57
|
```java
|
58
58
|
|
59
|
-
DateT
|
59
|
+
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMM");
|
60
60
|
|
61
61
|
|
62
62
|
|
1
いろいろ更新
test
CHANGED
@@ -1 +1,93 @@
|
|
1
|
+
難読化している最大の要因は、カレンダーから文字列への変換ですね。
|
2
|
+
|
3
|
+
[SimpleDateFormat](https://docs.oracle.com/javase/jp/6/api/java/text/SimpleDateFormat.html)を使えば、このインスタンスを1つ用意しておくだけで、文字列変換が1文で書けます。
|
4
|
+
|
5
|
+
```java
|
6
|
+
|
7
|
+
DateFormat format = new SimpleDateFormat("yyyyMM");
|
8
|
+
|
9
|
+
String now = format.format(calendar);
|
10
|
+
|
11
|
+
```
|
12
|
+
|
13
|
+
|
14
|
+
|
15
|
+
なお、他の方も回答していますが、年月を管理するのにわざわざCalendarを使う必要は無いのでは?
|
16
|
+
|
17
|
+
この操作に限定するなら、intで年と月をそれぞれ管理すればいいのでは?
|
18
|
+
|
19
|
+
```java
|
20
|
+
|
21
|
+
int fromym = 201501;
|
22
|
+
|
23
|
+
int toym = 201601
|
24
|
+
|
25
|
+
|
26
|
+
|
27
|
+
int year = fromym / 100;
|
28
|
+
|
29
|
+
int month = fromym % 100;
|
30
|
+
|
31
|
+
int cal = fromym;
|
32
|
+
|
33
|
+
while(cal <= toym){
|
34
|
+
|
35
|
+
System.out.println(cal);
|
36
|
+
|
37
|
+
month++;
|
38
|
+
|
39
|
+
if(month > 12){
|
40
|
+
|
41
|
+
year += month / 12;
|
42
|
+
|
43
|
+
month %= 12;
|
44
|
+
|
45
|
+
}
|
46
|
+
|
47
|
+
cal = year * 100 + month;
|
48
|
+
|
49
|
+
}
|
50
|
+
|
51
|
+
```
|
52
|
+
|
53
|
+
|
54
|
+
|
55
|
+
また、Calendarはバグがあるなど潜在的な問題があるので、Java8のAPIを使うことをおすすめします。
|
56
|
+
|
57
|
+
```java
|
58
|
+
|
59
|
+
DateTImeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMM");
|
60
|
+
|
61
|
+
|
62
|
+
|
63
|
+
//ベースが文字列なら、上のformatterを使ってparseメソッドを使うがここでは省略
|
64
|
+
|
65
|
+
YearMonth from = YearMonth.of(2015, 1);
|
66
|
+
|
67
|
+
YearMonth to = YearMonth.of(2016, 1);
|
68
|
+
|
69
|
+
ArrayList<YearMonth> yms = new ArrayList<>();
|
70
|
+
|
71
|
+
|
72
|
+
|
73
|
+
YearMonth now = from;
|
74
|
+
|
75
|
+
|
76
|
+
|
77
|
+
while(!to.isBefore(now)){
|
78
|
+
|
79
|
+
yms.add(now);
|
80
|
+
|
81
|
+
now = now.plus(1, ChronoUnit.MONTHS);
|
82
|
+
|
83
|
+
}
|
84
|
+
|
85
|
+
|
86
|
+
|
1
|
-
|
87
|
+
for(YearMonth ym : yms){
|
88
|
+
|
89
|
+
System.out.println(formatter.format(ym));
|
90
|
+
|
91
|
+
}
|
92
|
+
|
93
|
+
```
|