1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C# 日付計算 週の開始日と最終日

Last updated at Posted at 2016-02-18

日曜始まりと月曜始まりは確認、火曜日始まり以降は未確認。

コメントで指摘いただいているとおり次のコードには問題があります。
利用者の責任において、という前提ですが、検討される場合はコメントのコードから始めるとよいと思います。指摘いただいた方、ありがとうございます。

public static class DateTimeExtension
{
    /// <summary>
    /// 週の最初の曜日を指定して開始日を返す
    /// </summary>
    /// <param name="source"></param>
    /// <param name="start">週の最初の曜日</param>
    /// <returns></returns>
    public static DateTime FirstDayOfWeek(this DateTime source, DayOfWeek start)
    {
        if (start == DayOfWeek.Sunday)
        {
            return source.AddDays(DayOfWeek.Sunday - source.DayOfWeek);
        }
        else
        {
            var d = start - source.DayOfWeek;
            return source.AddDays((d > 0) ? d - 7 : d);    // MAGIC
        }
    }

    /// <summary>
    /// 週の最初の曜日を指定して最終日を返す
    /// </summary>
    /// <param name="source"></param>
    /// <param name="start">週の最初の曜日</param>
    /// <returns></returns>
    public static DateTime LastDayOfWeek(this DateTime source, DayOfWeek start)
    {
        if (start == DayOfWeek.Sunday)
        {
            return source.AddDays(DayOfWeek.Saturday - source.DayOfWeek);
        }
        else
        {
            var d = start - source.DayOfWeek;
            return source.AddDays((d == 1) ? 0 : 6 + d);    // MAGIC
        }
    }
}
1
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?