我如何在c#中找到一周的开始(包括周日和周一),只知道当前时间?

喜欢的东西:

DateTime.Now.StartWeek(Monday);

当前回答

步骤1:

创建静态类

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

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

第二步:使用这个类来确定一周的开始和结束日期

DateTime dt = TIMEE.StartOfWeek(DateTime.Now ,DayOfWeek.Monday);
DateTime dt1 = TIMEE.EndOfWeek(DateTime.Now, DayOfWeek.Sunday);

其他回答

把这些都放在一起,加上全球化并允许指定一周的第一天作为我们通话的一部分

public static DateTime StartOfWeek ( this DateTime dt, DayOfWeek? firstDayOfWeek )
{
    DayOfWeek fdow;

    if ( firstDayOfWeek.HasValue  )
    {
        fdow = firstDayOfWeek.Value;
    }
    else
    {
        System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
        fdow = ci.DateTimeFormat.FirstDayOfWeek;
    }

    int diff = dt.DayOfWeek - fdow;

    if ( diff < 0 )
    {
        diff += 7;
    }

    return dt.AddDays( -1 * diff ).Date;

}

稍微啰嗦一点,了解一下文化:

System.Globalization.CultureInfo ci = 
    System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
DayOfWeek today = DateTime.Now.DayOfWeek;
DateTime sow = DateTime.Now.AddDays(-(today - fdow)).Date;

c#中的模数对-1 mod 7(它应该是6,但c#返回-1)效果很差 所以…一个“一行程序”的解决方案是这样的:

private static DateTime GetFirstDayOfWeek(DateTime date)
{
    return date.AddDays(
        -(((int)date.DayOfWeek - 1) -
          (int)Math.Floor((double)((int)date.DayOfWeek - 1) / 7) * 7));
}

你可以使用优秀的Umbrella库:

using nVentive.Umbrella.Extensions.Calendar;
DateTime beginning = DateTime.Now.BeginningOfWeek();

然而,它们似乎已经将星期一存储为一周的第一天(参见属性nvent . umbrelga . extensions . calendar . defaultdatetimecalendarexextensions . weekbeginson),因此先前的本地化解决方案要好一些。不幸的。

编辑:仔细看看这个问题,雨伞似乎也能解决这个问题:

// Or DateTime.Now.PreviousDay(DayOfWeek.Monday)
DateTime monday = DateTime.Now.PreviousMonday(); 
DateTime sunday = DateTime.Now.PreviousSunday();

尽管值得注意的是,如果你在周一要求前一个周一,它会给你7天。但如果你使用BeginningOfWeek,这也是正确的,这似乎是一个错误:(。

这将给你前一个星期天(我想):

DateTime t = DateTime.Now;
t -= new TimeSpan ((int) t.DayOfWeek, 0, 0, 0);