C# 计算上周的开始和结束日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/658353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:11:11  来源:igfitidea点击:

Calculate previous week's start and end date

c#

提问by Henryk

What is the best way to calculate the previous week's start and end date in C#? I.e. today 18 March would result in 9 March (Monday last week) and 15 March (Sunday last week).

在 C# 中计算上周开始和结束日期的最佳方法是什么?即今天的 3 月 18 日将导致 3 月 9 日(上周的星期一)和 3 月 15 日(上周的星期日)。

I have seen this done with DayOfWeek and a switch statement to work out an offset but was wondering whether there is a more elegant way.

我已经看到使用 DayOfWeek 和 switch 语句来计算偏移量,但想知道是否有更优雅的方法。

采纳答案by bstoney

You can skip the while loop and use

您可以跳过while循环并使用

DateTime mondayOfLastWeek = date.AddDays( -(int)date.DayOfWeek - 6 );

This assumes you're using Monday as the first day of the week.

这假设您使用星期一作为一周的第一天。

回答by mqp

DayOfWeek weekStart = DayOfWeek.Monday; // or Sunday, or whenever
DateTime startingDate = DateTime.Today;

while(startingDate.DayOfWeek != weekStart)
    startingDate = startingDate.AddDays(-1);

DateTime previousWeekStart = startingDate.AddDays(-7);
DateTime previousWeekEnd = startingDate.AddDays(-1);

Read: Backtrack one day at a time until we're at the start of this week, and then subtract seven to get to the start of last week.

阅读:一次回溯一天,直到我们在本周的开始,然后减去 7 到上周的开始。

回答by Andy Rose

Using DayOfWeek would be a way of achieving this:

使用 DayOfWeek 将是实现这一目标的一种方式:

    DateTime date = DateTime.Now.AddDays(-7);
    while (date.DayOfWeek != DayOfWeek.Monday)
    {
        date = date.AddDays(-1);
    }

    DateTime startDate = date;
    DateTime endDate = date.AddDays(7);

回答by Simon

using Fluent DateTime https://github.com/FluentDateTime/FluentDateTime

使用 Fluent DateTime https://github.com/FluentDateTime/FluentDateTime

var dateTime = 1.Weeks().Ago();
var monday = dateTime.Previous(DayOfWeek.Sunday);
var sunday = dateTime.Next(DayOfWeek.Sunday);

回答by John M

You could create a DateTime Extension method, that can be used with a DayOfWeek parameter:

您可以创建一个 DateTime 扩展方法,该方法可以与 DayOfWeek 参数一起使用:

public static class DateTimeExtension
{
    public static DateTime GetPreviousWeekDay(this DateTime currentDate, DayOfWeek dow)
    {
        int currentDay = (int)currentDate.DayOfWeek, gotoDay = (int)dow;
        return currentDate.AddDays(-7).AddDays(gotoDay-currentDay);
    }        
}

Then use it as follows:

然后按如下方式使用它:

DateTime testDate = new DateTime(2017, 01, 21);

Console.WriteLine(testDate.GetPreviousWeekDay(DayOfWeek.Sunday));
Console.WriteLine(testDate.GetPreviousWeekDay(DayOfWeek.Saturday));

回答by nepdev

The accepted solution is actually not correct.

接受的解决方案实际上是不正确的。

You have to switch when the week "breaks", i.e. when it considers the week to end or start, and the formula in the accepted solution does not.

您必须在一周“中断”时切换,即当它认为一周结束或开始时,而接受的解决方案中的公式没有。

This is not so visible on a Monday as week start, but more so if you would consider Thursday the end of the week.

这在一周开始时的星期一不太明显,但如果您将星期四视为一周的结束,则更是如此。

Correct formula is (for a Thursday as ending day):

正确的公式是(以星期四作为结束日):

DateTime thu = date.AddDays(-(int)(date.AddDays(-5).DayOfWeek) -1);

For Monday, the -5 would switch to -2.

对于星期一,-5 将切换到 -2。

Example code to print out

打印输出示例代码

        String s = "";
        DateTime date = new DateTime(2017, 1, 1);
        for (int i = 0; i < 14; i++)
        {
            date = date.AddDays(1);
            DateTime thu = date.AddDays(-(int)(date.AddDays(-5).DayOfWeek) -1);
            DateTime mon = date.AddDays(-(int)(date.AddDays(-2).DayOfWeek) -1);
            s += date.ToString() + " - Thu: " + thu.ToString() + " - Mon: " + mon.ToString() + "\r\n";
        }
        Console.WriteLine(s);

回答by Martin

Current accepted answer will fail for Sundays by giving the Monday of the current week instead of last weeks Monday. (code with unit tests output)

当前接受的答案将在星期日失败,因为它给出了本周的星期一而不是上周的星期一。(带有单元测试输出的代码)

DateTime mondayOfLastWeek = date.AddDays( -(int)date.DayOfWeek - 6 );
//Failed to get start of last-week from date-time: 2020-03-01T00:00:00.0000000Z
//  Expected: 2020-02-17 00:00:00.000
//  But was:  2020-02-24 00:00:00.000

The following bit of code addresses this issue:

下面的代码解决了这个问题:

var dayOfWeek = (int) date.DayOfWeek - 1;
if (dayOfWeek < 0) dayOfWeek = 6;

var thisWeeksMonday = date.AddDays(-dayOfWeek).Date;
var lasWeeksMonday = thisWeeksMonday.AddDays(-7);

which can be reduced to a one-liner should you so desire (I do not recommend using this barely readable code...):

如果您愿意,可以将其简化为单行(我不建议使用这种几乎不可读的代码......):

var mondayOfLastWeek  = date.AddDays(-(7 + ((int)date.DayOfWeek - 1 == -1 ? 6 : (int)date.DayOfWeek - 1)));