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

喜欢的东西:

DateTime.Now.StartWeek(Monday);

当前回答

以下是一些答案的组合。它使用一个扩展方法,允许传入区域性。如果没有传入,则使用当前区域性。这将为它提供最大的灵活性和重用性。

/// <summary>
/// Gets the date of the first day of the week for the date.
/// </summary>
/// <param name="date">The date to be used</param>
/// <param name="cultureInfo">If none is provided, the current culture is used</param>
/// <returns>The date of the beggining of the week based on the culture specifed</returns>
public static DateTime StartOfWeek(this DateTime date, CultureInfo cultureInfo=null) =>
    date.AddDays(-1 * (7 + (date.DayOfWeek - (cultureInfo ?? CultureInfo.CurrentCulture).DateTimeFormat.FirstDayOfWeek)) % 7).Date;

使用示例:

public static void TestFirstDayOfWeekExtension() {
    DateTime date = DateTime.Now;
    foreach(System.Globalization.CultureInfo culture in CultureInfo.GetCultures(CultureTypes.UserCustomCulture | CultureTypes.SpecificCultures)) {
        Console.WriteLine($"{culture.EnglishName}: {date.ToShortDateString()} First Day of week: {date.StartOfWeek(culture).ToShortDateString()}");
    }
}

其他回答

你可以使用优秀的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 startAtMonday = DateTime.Now.AddDays(DayOfWeek.Monday - DateTime.Now.DayOfWeek);

在周日

DateTime startAtSunday = DateTime.Now.AddDays(DayOfWeek.Sunday- DateTime.Now.DayOfWeek);

通过这种方式计算,您可以选择一周中的哪一天表示新一周的开始(在示例中,我选择了星期一)。

请注意,对星期一进行这个计算将得到当前的星期一,而不是以前的星期一。

//Replace with whatever input date you want
DateTime inputDate = DateTime.Now;

//For this example, weeks start on Monday
int startOfWeek = (int)DayOfWeek.Monday;

//Calculate the number of days it has been since the start of the week
int daysSinceStartOfWeek = ((int)inputDate.DayOfWeek + 7 - startOfWeek) % 7;

DateTime previousStartOfWeek = inputDate.AddDays(-daysSinceStartOfWeek);

让我们结合文化安全答案和扩展方法答案:

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
        DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
        return DateTime.Today.AddDays(-(DateTime.Today.DayOfWeek- fdow));
    }
}

我尝试了几次,但我没有解决从星期一开始的一周的问题,导致我的下一个星期一是星期天。所以我对它做了一些修改,让它与下面的代码一起工作:

int delta = DayOfWeek.Monday - DateTime.Now.DayOfWeek;
DateTime monday = DateTime.Now.AddDays(delta == 1 ? -6 : delta);
return monday;