【解決方法】月の開始日と終了日、および 2 つの日付の間の各月の日数


パラメータとして次の日付があります

開始日: 2016 年 2 月 15 日
終了日: 2017 年 2 月 14 日

期待される出力:

MonthStart MonthEnd NoOfDays
2016/02/15 2016/02/29 15
2016/03/01 2016/03/31 31
2016 年 4 月 1 日 2016 年 4 月 30 日 30
2016/05/01 2016/05/31 31
2016/06/01 2016/06/30 30
2016/07/01 2016/07/31 31
2016 年 8 月 1 日 2016 年 8 月 31 日 31
2016 年 9 月 1 日 2016 年 9 月 30 日 30
2016 年 10 月 1 日 2016 年 10 月 31 日 31
2016 年 11 月 1 日 2016 年 11 月 30 日 30
2016/12/01 2016/12/31 31
2017/01/01 2017/01/31 31
2017/02/01 2017/02/14 14

私が試したこと:

私はこれが初めてで、期待される出力を超えるために助けが必要です。

解決策 2

これを試して..

C#
public static void PrintDates(DateTime start, DateTime end)
{
while (start < end)
{
var lastDayOfMonth = DateTime.DaysInMonth(start.Year, start.Month);
var howManyDays = lastDayOfMonth - start.Day;
var monthEndDate=start.AddDays(howManyDays);
if(end<=monthEndDate)
Console.WriteLine("{0} {1} {2}", start.ToShortDateString(), end.ToShortDateString(), (end - start).TotalDays + 1);
else
Console.WriteLine("{0} {1} {2}", start.ToShortDateString(), monthEndDate.ToShortDateString(), (monthEndDate - start).TotalDays + 1);
start = monthEndDate.AddDays(1);               
}
}
C#
var start = new DateTime(2016, 02, 15);
var end = new DateTime(2017, 02, 14);
PrintDates(start, end);

解決策 1

DateTime.Add などを使用した日付計算と、TimeSpan クラスに慣れてください。 任意の月について、日付として 1 を持ち、指定された月と年を持つ DateTime クラスを作成することで、開始を見つけることができます。 その月がいつ終わるかを調べるには、月の最初に 1 か月を足してから 1 日を引きます (-1 日を足します)。

これにより、開始日と終了日が得られるので、毎日行って使用します DateTime.DayOfWeek[^] 平日かどうかを確認し、平日の場合は実行中のカウントに 1 を追加します。 それを関数にすると、開始日と終了日の間で毎月実行するだけで済みます。

解決策 3

jinesh sam 解決策は永遠にループしていたので、小さな変更を加えました。
if (endDate <= monthEndDate) では、startDate = startDate.AddDays(daysInMonth); を追加する必要があります。 ループを停止します。
スクリプト Jinesh に感謝します。プロジェクトの時間を大幅に節約できます。

var startDate = new DateTime(2022, 01, 01);
var endDate = new DateTime(2022, 12, 31);
        
while (startDate < endDate)
{
    var lastDayOfMonth = DateTime.DaysInMonth(startDate.Year, startDate.Month);
            
    var daysInMonth = lastDayOfMonth - startDate.Day;
            
    var monthEndDate = startDate.AddDays(daysInMonth);

    if (endDate <= monthEndDate)
    {
        Console.WriteLine("{0} {1} {2}", startDate.ToShortDateString(), endDate.ToShortDateString(), (endDate - startDate).TotalDays + 1);
        startDate = startDate.AddDays(daysInMonth);
    }
    else
    {
        Console.WriteLine("{0} {1} {2}", startDate.ToShortDateString(), monthEndDate.ToShortDateString(), (monthEndDate - startDate).TotalDays + 1);
        startDate = monthEndDate.AddDays(1);
    }
}

コメント

タイトルとURLをコピーしました