繁体   English   中英

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

[英]Is there a more efficient way to get the previous Monday for a given date in C#

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

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;
}

}

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

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

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

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

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

GregorianCalendar gc = new GregorianCalendar(); 
int weekno = gc.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

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

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

你为什么不使用DateTimePicker控件? 它会告诉您用户所选日期的日期。 然后你可以简单地减去不。 从星期一到星期几的日子。 例如:我正在使用DateTimePicker控件并将其命名为dtpTemp。 使用的事件是

dtpTemp_ValueChanged()

dtpTemp.Value.DayOfWeek - 会给你一天:星期二,星期三,星期四等。

那么你可以相应地使用以下代码与switch case:

dtpTemp.Value.AddDays(num); 星期一的约会

这里num将具有-ve值,这取决于上面计算的日期。 值:周二为-1,周三为-2,周四为-3,依此类推。

另外,使用datetimepicker也会对UI本身产生积极影响。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM