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

So, I have an application that needs to get the date focus so that it can work properly. Given a specific date, to focus on it, you need to know what week it is. I count weeks by dates on Monday. And I wonder if my attention is too focused on Mondays.

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

}

The system launches a 4-week schedule starting from the first tax week, and it needs to behave differently depending on where it is on the schedule. So you can see ...

  • Get the date from the user (say userDate)
  • The call to userDate=userDate.PreviousMonday(); get to Monday of the week is given - where Sunday is the end of the week.
  • userDate.PeriodWeek(); , , 1 4.

GetTaxWeek , ... , , .

? .

+3
2

, , GregorianCalendar System.Globalization. :

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

, , . , , - , . , .

, - , , , :)

+6

DateTimePicker? . . , . : DateTimePicker dtpTemp.

dtpTemp_ValueChanged()

dtpTemp.Value.DayOfWeek - : , , ..

:

dtpTemp.Value.AddDays(num);,

num -ve, , . : -1 , -2 , -3 ..

plus, datetimepicker .

0

Source: https://habr.com/ru/post/1771272/


All Articles