一尘不染

我如何获取一周中开始的DateTime?

c#

我如何只知道C#中的当前时间来查找一周的开始(星期日和星期一)?

就像是:

DateTime.Now.StartWeek(Monday);

阅读 248

收藏
2020-05-19

共1个答案

一尘不染

使用扩展方法。他们是一切的答案,你知道的!;)

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
        return dt.AddDays(-1 * diff).Date;
    }
}

可以如下使用:

DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
2020-05-19