是否有更有效的方法来获取C#中给定日期的上一个星期一

Pau*_*bra 3 c# datetime

所以我有一个应用程序需要获取日期焦点,以便它可以正常运行.鉴于要关注的特定日期,需要知道它在哪一周.我根据周一日期计算周数.而且我想知道我对星期一的关注是否过度.

public static DateTime PreviousMonday(this DateTime dt)
{
    var dateDayOfWeek = (int)dt.DayOfWeek;
    if (dateDayOfWeek==0)
    {
        dateDayOfWeek = dateDayOfWeek + 7; 
    }
    var alterNumber = dateDayOfWeek - ((dateDayOfWeek*2)-1);

    return dt.AddDays(alterNumber);
}

/// <summary>
/// Personal tax week starts on the first Monday after the week with 6th April in unless 6th April is a Monday in 
/// which case that starts the first week. In a leap year this means you can have a week 53 which due to the mod 4 approach of calculating 
/// flexi week means you get a 5 week flexi period.
/// As such this method forces the weeks into the range 1 - 52 by finding the week number for the week containing 6th April and
/// the number for the current week. Treating the 6th April week as week 1 and using the difference to calculate the tax week.
/// </summary>
public static int GetTaxWeek(this DateTime dt)
{
    var startTaxYear = GetActualWeekNumber(new DateTime(DateTime.Now.Year, 4, 6));
    var thisWeekNumber = GetActualWeekNumber(dt);
    var difference = thisWeekNumber - startTaxYear;
    return difference < 0 ? 53 + difference : difference + 1;
}

private static int GetActualWeekNumber(DateTime dt)
{
    var ci = System.Threading.Thread.CurrentThread.CurrentCulture;
    var cal = ci.Calendar;
    var calWeekRule = ci.DateTimeFormat.CalendarWeekRule;
    var fDoW = ci.DateTimeFormat.FirstDayOfWeek;
    return cal.GetWeekOfYear(dt, calWeekRule, fDoW);
}

public static int PeriodWeek(this DateTime dt)
{
    var rawPeriodWeek = GetTaxWeek(dt) % 4;
    return rawPeriodWeek == 3 ? 1 : rawPeriodWeek + 2;
}
Run Code Online (Sandbox Code Playgroud)

}

系统从第一个纳税周开始运行一个滚动的4周计划,并且需要根据计划中的位置而有所不同.所以你可以看到......

  1. 从用户那里获取日期(比如说userDate)
  2. 打电话userDate=userDate.PreviousMonday(); 到达周一周一 - 周日是周末
  3. 拨打userDate.PeriodWeek();并获取您所在的时间段,从1到4.

GetTaxWeek是公开的,因为它在其他地方使用...我也替换日期,因为它被多次使用,我不想记得多次更改它.

我可以看到树木吗?或者是否有更多无错误的方法来做到这一点.

Øyv*_*hen 6

我认为您可以使用GregorianCalendar内部大大简化您的代码System.Globalization.在这里,您可以获得给定日期的周数,如下所示:

GregorianCalendar gc = new GregorianCalendar(); 
int weekno = gc.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
Run Code Online (Sandbox Code Playgroud)

您在此处看到,您可以根据当地规则提供有关如何计算周数的规则.就像在挪威一样,我们将星期一作为我们的第一个工作日,而一年中的第一周是有四天或更长时间的第一周.将此设置为您的特定于文化的规则以获取正确的周数.

你的一些具体处理你仍然需要手工完成,但有些杂乱的东西可以用这个去除至少:)