This code calculates the date of the **previous Friday** before...

July 1, 2025 at 05:56 PM

var now = Model.Payslip.PaymentPeriod.DateStart; // Calculate the first date of the following month var firstOfNextMonth = new DateTime(now.Year, now.Month, 1).AddMonths(1); // Find the previous Friday var previousFriday = firstOfNextMonth.AddDays(-(int)firstOfNextMonth.DayOfWeek - 2); if (previousFriday.DayOfWeek > DayOfWeek.Friday) { previousFriday = previousFriday.AddDays(-7); }

This code calculates the date of the previous Friday before the first day of the following month (relative to a given starting date). Here's a detailed explanation of what each part of the code does:

  1. var now = Model.Payslip.PaymentPeriod.DateStart;:

    • Retrieves the starting date from some object or data source (e.g., a payslip's payment period).
  2. var firstOfNextMonth = new DateTime(now.Year, now.Month, 1).AddMonths(1);:

    • Constructs a DateTime object representing the first day of the current month (now.Year, now.Month, 1), and then advances it by one month using .AddMonths(1).
    • This gives the first date of the next month.
  3. Find the previous Friday relative to firstOfNextMonth:

    var previousFriday = firstOfNextMonth.AddDays(-(int)firstOfNextMonth.DayOfWeek - 2);
    
    • (int)firstOfNextMonth.DayOfWeek: Converts the day of the week (e.g., Sunday = 0, Monday = 1, ..., Saturday = 6) into an integer.
    • Subtracting this integer from the firstOfNextMonth shifts the date backwards to Sunday of that week (or earlier).
    • Subtracting an additional -2 adjusts the date to Friday of that week.
      • For example, if the first of the next month lands on a Monday (DayOfWeek = 1), this subtracts -(1 + 2) = -3 days, moving the date back to Friday.
  4. Adjust for cases where the calculated date does not fall on a Friday:

    if (previousFriday.DayOfWeek > DayOfWeek.Friday)
    {
        previousFriday = previousFriday.AddDays(-7);
    }
    
    • If the result of the above calculation (previousFriday) somehow lands on a day after Friday (e.g., Saturday), this further subtracts 7 days to return to the correct Friday of the previous week.

Final Result:

The variable previousFriday will contain the last Friday before the first day of the following month relative to the starting date (now).

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node