物忘れの激しいエンジニアのメモ

スクレイピング、映像系、アプリ、webなど...

【Unity】 ArgumentOutOfRangeException: Year, Month, and Day parameters describe an un-representable DateTime.

背景

「明日の0時までのカウントダウンを表示する」というのをやりたかった。 問題のコードはこちらです。

        current = DateTime.Now;
        tomorrow = new DateTime(current.Year, current.Month, current.Day + 1);

tomorrowは時間を指定せず初期化すると0時0分0秒となるので、 DateTime.Nowtomorrowの差分が明日までの時間になりますね。

ところがある日、エラーが出ていることに気付きました...

ArgumentOutOfRangeException: Year, Month, and Day parameters describe an un-representable DateTime.

原因

エラーの通りDatetimeの初期化に使っている数値がOutOfRangeということですね...

エラーが出た日は9月30日。つまりtomorrowの初期化に9月31日(存在しない)を指定していたのですね...

(リリース前に気づけてよかった)

解決策

AddDays()を使いましょう!

        current = DateTime.Now;
        tomorrow = new DateTime(current.Year, current.Month, current.Day).AddDays(1);

まとめ

AddMonths()とかがわざわざあるのはこういう日時特有の計算が楽になるためです!

変なことせず素直にこういう関数を使っていきましょう!

(自戒を込めて)