查找上周完成周的结束日期

时间:2011-02-22 15:30:36

标签: c# .net

对于任何指定日期,如果您的周从周日到周六,您如何找到上一个完整周的周结束日期?

6 个答案:

答案 0 :(得分:19)

DateTime StartOfWeek = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);
DateTime EndOfLastWeek = StartOfWeek.AddDays(-1);

答案 1 :(得分:2)

DateTime givenDate; // = ...
int daysToOffset = ((int)givenDate.DayOfWeek + 1) * -1;
DateTime lastDayOfLastCompletedWeek = givenDate.AddDays(daysToOffset);

答案 2 :(得分:1)

.NET DateTimes公开DayOfWeek属性。在这种情况下,您可以利用它:

var currDay = DateTime.Today.DayOfWeek;
//currday is now an enumeration with Sunday=0, Saturday=6
//We can cast that to a number and subtract to get to the previous Saturday
var EndOfLastWeek = DateTime.Today.AddDays(((int)currDay+1)*-1);

答案 3 :(得分:1)

    public static DateTime EndOfWeek(DateTime dateTime)
    {
        DateTime start = StartOfWeek(dateTime);

        return start.AddDays(6);
    }

    public static DateTime StartOfWeek(DateTime dateTime)
    {
        int days = dateTime.DayOfWeek - DayOfWeek.Monday; 

        if (days < 0) 
            days += 7;

        return dateTime.AddDays(-1 * days).Date;
    }

要查找上周结束,请致电:

    DateTime endPrevWeek = StartOfWeek(DateTime.Today).AddDays(-1);

答案 4 :(得分:0)

如果您想指定哪一天是星期结束,并且您不想担心系统定义为一周的默认开始日期,请使用此方法:

private static DateTime GetPreviousSpecifiedDayOfWeek(DateTime dt, DayOfWeek day)
    {
        if (dt.DayOfWeek == day)
        {
            return dt;
        }

        while (dt.DayOfWeek != day)
        {
            dt = dt.AddDays(-1);
        }

        return dt;
    }

答案 5 :(得分:0)

这是一个通用的 .NET 方法:

public static DateTime GetPreviousDayDate(DateTime referenceDate, DayOfWeek day = DayOfWeek.Saturday)
{
    // DayOfWeek: https://docs.microsoft.com/en-us/dotnet/api/system.dayofweek?view=net-5.0
    // Sunday = 0, Monday = 1, ..., Saturday = 6
    // e.g. if today is Wednesday (3), we subtract 4 days to get to the prior Saturday (6)
    // because 3 - 6 = -3 + 7 = 4
    // e.g. if today is Saturday (6), we substract 3 days to get to the prior Wednesday (3)
    // because 6 - 3 = 3

    int DaysToSubtract = (int)referenceDate.DayOfWeek - (int)day;

    // If the number of days to subtract based on the ordinal of the day of the week is negative, add 7 days back
    if (DaysToSubtract < 1) DaysToSubtract += 7;

    return referenceDate.AddDays(DaysToSubtract * -1);
}