小编典典

如何获得一周开始的日期时间?

all

如何在 C# 中仅知道当前时间找到一周的开始时间(周日和周一)?

就像是:

DateTime.Now.StartWeek(Monday);

阅读 98

收藏
2022-03-10

共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);
2022-03-10