VB.NETでは日付の差を求める際に、DateDiff関数がよく利用されます。しかし、経過年月を求める場合は注意が必要です。
この記事では、DateDiff関数の動作と、用途に応じた正しい経過年月の求め方を紹介します。
目次
DateDiff関数が期待通りにならないケース
以下の例は、DateDiff関数が期待通りにならないケースです。
Dim startDate As Date = #2026/1/31#
Dim endDate As Date = #2026/2/1#
Dim monthDiff As Integer =
DateDiff(DateInterval.Month, startDate, endDate)
Console.WriteLine(monthDiff & "か月")
実行結果
1か月
しかし、実際の経過日数は1日です。
DateDiff関数の DateInterval.Month は「月の境界を何回跨いだか」を返します。
1月から2月に入ったため「1か月」と判定されました。
次のケースは、勤続年数や契約期間を求める場合のDateDiff関数の動きです。
Dim startDate As Date = #2024/6/15#
Dim endDate As Date = #2026/8/14#
Dim monthDiff As Integer =
DateDiff(DateInterval.Month, startDate, endDate)
Console.WriteLine(monthDiff & "か月")
実行結果
26か月
しかし、まだ 2026/8/15 に到達していません。実際は25か月(2年1か月)です。
このように、DateDiff関数だけでは実際の経過期間を正確に表現できないことがあります。
満了した経過月数を求めたい場合
以下は、年齢や勤続年数の月数を求める場合です。
Dim startDate As Date = #2024/6/15#
Dim endDate As Date = #2026/8/14#
Dim months As Integer =
(endDate.Year - startDate.Year) * 12 +
(endDate.Month - startDate.Month)
If endDate.Day < startDate.Day Then
months -= 1
End If
Console.WriteLine(months & "か月")
実行結果
25か月
○年○か月で取得したい場合
以下は、「○年○か月」で出力したい場合です。
Dim startDate As Date = #2024/6/15#
Dim endDate As Date = #2026/8/14#
Dim years As Integer = endDate.Year - startDate.Year
Dim months As Integer = endDate.Month - startDate.Month
If endDate.Day < startDate.Day Then
months -= 1
End If
If months < 0 Then
years -= 1
months += 12
End If
Console.WriteLine($"{years}年 {months}か月")
実行結果
2年 1か月
まとめ
DateDiff関数は、日付の差分を簡単に取得できる便利な関数ですが、Month や Year を指定した場合は「実際に経過した年月」ではなく、「月や年の境界を何回跨いだか」を基準に計算されます。そのため、年齢計算や勤続年数、契約期間のような「満了した年月」を求める用途では、期待した結果にならないケースがあります。
経過日数であれば DateDiff(DateInterval.Day) を利用して問題ありませんが、経過年月を正確に求める場合は、年月の差分を算出したうえで日付を考慮した補正を行う必要があります。
以上、DateDiff関数の動作と、用途に応じた正しい経過年月の求め方について解説しました。