LoginSignup
3
1

More than 1 year has passed since last update.

満経過月数を計算するロジック(Ruby)

Last updated at Posted at 2021-08-15

経過月数(満月)を計算するロジックについて解説します。(あまり記事がなかった)
具体的に言うと以下のようなロジック。

start:2021年01月15日
end:2021年02月14日
→経過月数0を返す

start:2021年01月15日
end:2021年02月15日
→経過月数1を返す

start:2021年01月15日
end:2022年03月15日
→経過月数14を返す

コード

IN:開始日(start),終了日(end) :Date型
OUT:満経過月数

def calculate_diff_months(start, end)
  (end.year - start.year) * 12 + end.month - start.month - (end.day >= start.day ? 0 : 1)
end

コードの解説

■年の計算
(end.year - start.year) * 12
→ 年の差分を求めて月変換

■月の計算
end.month - start.month
→ そのまま月の差分を求める
ここまではシンプル。

■日付の計算
(end.day >= start.day ? 0 : 1)
終了の日付>=開始の日付の場合はそのまま月数を出したいので0で計算
終了の日付<開始の日付の場合は月数をマイナス-1にしたいので1で計算

閏年のこととか考えて最初、戸惑いましたが以外とシンプルに実装できました。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1