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

喜欢的东西:

DateTime.Now.StartWeek(Monday);

当前回答

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

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;

}

其他回答

在c#中试试这个。使用这段代码,您可以获得给定一周的第一个日期和最后一个日期。在这里,周日是第一天,周六是最后一天,但您可以根据您的文化设置这两天。

DateTime firstDate = GetFirstDateOfWeek(DateTime.Parse("05/09/2012").Date, DayOfWeek.Sunday);
DateTime lastDate = GetLastDateOfWeek(DateTime.Parse("05/09/2012").Date, DayOfWeek.Saturday);

public static DateTime GetFirstDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)
{
    DateTime firstDayInWeek = dayInWeek.Date;
    while (firstDayInWeek.DayOfWeek != firstDay)
        firstDayInWeek = firstDayInWeek.AddDays(-1);

    return firstDayInWeek;
}

public static DateTime GetLastDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)
{
    DateTime lastDayInWeek = dayInWeek.Date;
    while (lastDayInWeek.DayOfWeek != firstDay)
        lastDayInWeek = lastDayInWeek.AddDays(1);

    return lastDayInWeek;
}

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

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;

我能想到的最快方法是:

var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);

如果您希望将一周中的任何一天作为您的开始日期,您所需要做的就是在结束时添加DayOfWeek值

var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday);

var tuesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Tuesday);

这可能有点黑,但你可以将. dayofweek属性转换为int(它是一个枚举,因为它的底层数据类型没有改变,它默认为int),并使用它来确定一周的前一周。

它显示DayOfWeek枚举中指定的周从周日开始,因此如果将这个值减去1,就等于周一离当前日期有多少天。我们还需要将周日(0)映射为7,因此给定1 - 7 = -6,周日将映射到前一个周一:-

DateTime now = DateTime.Now;
int dayOfWeek = (int)now.DayOfWeek;
dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek;
DateTime startOfWeek = now.AddDays(1 - (int)now.DayOfWeek);

前一个星期天的代码更简单,因为我们不需要做这样的调整:-

DateTime now = DateTime.Now;
int dayOfWeek = (int)now.DayOfWeek;
DateTime startOfWeek = now.AddDays(-(int)now.DayOfWeek);

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

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