LoginSignup
0
0

More than 1 year has passed since last update.

C#のDateTime型のAddMonthsで月末の日に1ヵ月を加算する場合の月末に丸められる動作

Last updated at Posted at 2023-01-28

まとめ(実測結果)

  • C#のDateTime型のAddMonthsで月末の日にNヵ月を加算すると、
    • 加算後の日付が月内を超える場合は月末の日に丸められ(1/31(月末)→2/28(丸め)等)、
    • 月内を超えない場合は加算前と同日を維持する(2/28(月末)→3/28(同日、非月末)等)

テストコード

Program 2301-2 AddMonthsの月末丸め動作テスト.cs
using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            /* 結果: 
DateTimeのAddMonthsで月末の日にNヵ月を加算すると、
加算後の日付が月内を超える場合は月末の日に丸められ(1/31(月末)→2/28(丸め)等)、
月内を超えない場合は加算前と同日を維持する(2/28(月末)→3/28(同日、非月末)等)

2023/02/28 0:00:00
2023/03/31 0:00:00
2023/03/28 0:00:00
2023/05/30 0:00:00
2023/05/31 0:00:00
            */

            Func<string, DateTime> DT = DateTime.Parse;
            Console.WriteLine($"{DT("2023/01/31").AddMonths(1)}");
            Console.WriteLine($"{DT("2023/01/31").AddMonths(2)}");
            Console.WriteLine($"{DT("2023/02/28").AddMonths(1)}");
            Console.WriteLine($"{DT("2023/04/30").AddMonths(1)}");
            Console.WriteLine($"{DT("2023/01/31").AddMonths(4)}");
        }
    }
}

環境

Microsoft Visual Studio Community 2019 Version 16.11.22
VisualStudio.16.Release
Microsoft .NET Framework
Version 4.8.04084
image.png

0
0
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
0
0