Javaで2つの入力された値に対して月数算出を行うメソッド実装に関する質問です。
以下のようなメソッドを実装しようとしていますが、苦戦しており、質問した次第です。
★入力値「2/29(FROM)」の一か月後は、入力値「3/2931(TO)」の範囲として「1」の値を呼び出し元に返すメソッド★31(TO)⇒「1」を返す
※2/29(FROM)と3/29
※2/29(FROM)と4/1(TO)⇒ 1か月以上となり「2」を返す
2/1と3/1などの月初めの比較は分かりやすいのですが、
2/29と3/31のような月末は判定が難しく、どのように実装すればよいでしょうか---。
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/07/07 15:15
退会済みユーザー
2016/07/07 16:13
回答4件
0
A-pZさんのとかなり似ていますが、YearMonth
を使ったバージョンです。
返す値がlong
になってしまうのが微妙かも。
lang
1// Java8以降 2 3// import java.time.YearMonth; 4// import java.time.format.DateTimeFormatter; 5// import java.time.temporal.ChronoUnit; 6 7public static long countMonths(String fromDateString, String toDateString) { 8 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); 9 YearMonth fromYM = YearMonth.parse(fromDateString, formatter); 10 YearMonth toYM = YearMonth.parse(toDateString, formatter); 11 return ChronoUnit.MONTHS.between(fromYM, toYM); 12}
投稿2016/07/08 00:18
総合スコア9388
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
0
開始日が月末の時だけ特殊処理すればいいわけですよね?
java
1import java.time.LocalDate; 2import java.time.temporal.ChronoUnit; 3 4public class Q40424 { 5 6 public static void main(String[] args) { 7 LocalDate from = LocalDate.of(2016, 2, 29); 8 LocalDate to = LocalDate.of(2016, 3, 28); 9 for(int i = 0; i < 5; i++){ 10 System.out.println(from + " -> " + to + " = " + countMonths(from, to)); 11 to = to.plusDays(1); 12 } 13 } 14 15 public static int countMonths(LocalDate from, LocalDate to){ 16 int count = (int) from.until(to, ChronoUnit.MONTHS); 17 //fromが月末、かつtoの日がfromの月末日よりあとの場合はそのままの月数を返す 18 if(from.getDayOfMonth() == from.lengthOfMonth() 19 && to.getDayOfMonth() >= from.getDayOfMonth()){ 20 return count; 21 } else { 22 return count + 1; 23 } 24 } 25 26} 27
出力
2016-02-29 -> 2016-03-28 = 1
2016-02-29 -> 2016-03-29 = 1
2016-02-29 -> 2016-03-30 = 1
2016-02-29 -> 2016-03-31 = 1
2016-02-29 -> 2016-04-01 = 2
投稿2016/07/07 18:10
総合スコア20649
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
0
ベストアンサー
Java8で簡素に書くと、
java
1import java.time.LocalDate; 2import java.time.format.DateTimeFormatter; 3 4public class MonthDiff { 5 6 public static int diff(String fromValue, String toValue) { 7 8 // 入力される日付のフォーマットは yyyy/MM/dd 形式であること 9 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); 10 LocalDate fromDate = LocalDate.parse(fromValue, formatter); 11 LocalDate toDate = LocalDate.parse(toValue, formatter); 12 13 int fromMonth = fromDate.getMonthValue(); 14 int toMonth = toDate.getMonthValue(); 15 16 return toMonth - fromMonth; 17 } 18}
投稿2016/07/07 16:30
総合スコア12011
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/04/06 07:01
2020/04/06 07:55
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。