質問するログイン新規登録

回答編集履歴

3

重大なミス

2016/06/24 17:06

投稿

swordone
swordone

スコア20675

answer CHANGED
@@ -2,7 +2,7 @@
2
2
  [SimpleDateFormat](https://docs.oracle.com/javase/jp/6/api/java/text/SimpleDateFormat.html)を使えば、このインスタンスを1つ用意しておくだけで、文字列変換が1文で書けます。
3
3
  ```java
4
4
  DateFormat format = new SimpleDateFormat("yyyyMM");
5
- String now = format.format(calendar);
5
+ String now = format.format(calendar.getTime());
6
6
  ```
7
7
 
8
8
  なお、他の方も回答していますが、年月を管理するのにわざわざCalendarを使う必要は無いのでは?

2

スペルミス

2016/06/24 17:06

投稿

swordone
swordone

スコア20675

answer CHANGED
@@ -27,7 +27,7 @@
27
27
 
28
28
  また、Calendarはバグがあるなど潜在的な問題があるので、Java8のAPIを使うことをおすすめします。
29
29
  ```java
30
- DateTImeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMM");
30
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMM");
31
31
 
32
32
  //ベースが文字列なら、上のformatterを使ってparseメソッドを使うがここでは省略
33
33
  YearMonth from = YearMonth.of(2015, 1);

1

いろいろ更新

2016/06/24 15:12

投稿

swordone
swordone

スコア20675

answer CHANGED
@@ -1,1 +1,47 @@
1
+ 難読化している最大の要因は、カレンダーから文字列への変換ですね。
2
+ [SimpleDateFormat](https://docs.oracle.com/javase/jp/6/api/java/text/SimpleDateFormat.html)を使えば、このインスタンスを1つ用意しておくだけで、文字列変換が1文で書けます。
3
+ ```java
4
+ DateFormat format = new SimpleDateFormat("yyyyMM");
5
+ String now = format.format(calendar);
6
+ ```
7
+
8
+ なお、他の方も回答していますが、年月を管理するのにわざわざCalendarを使う必要は無いのでは?
9
+ この操作に限定するなら、intで年と月をそれぞれ管理すればいいのでは?
10
+ ```java
11
+ int fromym = 201501;
12
+ int toym = 201601
13
+
14
+ int year = fromym / 100;
15
+ int month = fromym % 100;
16
+ int cal = fromym;
17
+ while(cal <= toym){
18
+ System.out.println(cal);
19
+ month++;
20
+ if(month > 12){
21
+ year += month / 12;
22
+ month %= 12;
23
+ }
24
+ cal = year * 100 + month;
25
+ }
26
+ ```
27
+
28
+ また、Calendarはバグがあるなど潜在的な問題があるので、Java8のAPIを使うことをおすすめします。
29
+ ```java
30
+ DateTImeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMM");
31
+
32
+ //ベースが文字列なら、上のformatterを使ってparseメソッドを使うがここでは省略
33
+ YearMonth from = YearMonth.of(2015, 1);
34
+ YearMonth to = YearMonth.of(2016, 1);
35
+ ArrayList<YearMonth> yms = new ArrayList<>();
36
+
37
+ YearMonth now = from;
38
+
39
+ while(!to.isBefore(now)){
40
+ yms.add(now);
41
+ now = now.plus(1, ChronoUnit.MONTHS);
42
+ }
43
+
1
- Java8のYearMonthクラスを使ってみては?
44
+ for(YearMonth ym : yms){
45
+ System.out.println(formatter.format(ym));
46
+ }
47
+ ```