[英]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周計划,並且需要根據計划中的位置而有所不同。 所以你可以看到......
userDate
) userDate=userDate.PreviousMonday();
到達周一周一 - 周日是周末 userDate.PeriodWeek();
從1到4獲取您所在的時間段。 GetTaxWeek是公開的,因為它在其他地方使用...我也更換日期,因為它被多次使用,我不想記得多次更改它。
我可以看到樹木嗎? 或者是否有更多無錯誤的方法來做到這一點。
我認為您可以使用System.Globalization
的GregorianCalendar
大大簡化您的代碼。 在這里,您可以獲得給定日期的周數,如下所示:
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.