Home > Software design >  How to get week ending date using current week?
How to get week ending date using current week?

Time:12-07

I'm trying to get the week ending date using the current week. My problem is when the week ending date is not Friday. For ex. for the month of January 2023, the week ending date for week 5 is 31 which is Tuesday and my current code is returning Feb. 3 which is the Friday of that week.

This is the code that I've tried so far.

var today = DateTime.Today;
DateTime weekEndingDate = today.AddDays(-(int)today.DayOfWeek).AddDays(5);

What I need is when the week ending date is fall in Tuesday, It will return Tuesday.

CodePudding user response:

Brute force.

using System;

DateTime dt = DateTime.Now;

var eow = GetEndOfWeek(dt);

Console.WriteLine(eow.ToString("D"));

dt = new DateTime(2022, 12, 31); // new years eve - on a Saturday

eow = GetEndOfWeek(dt);
Console.WriteLine(eow.ToString("D"));

DateTime GetEndOfWeek(DateTime date, DayOfWeek endOfWeek = DayOfWeek.Friday)
{
    if (date.DayOfWeek == endOfWeek) return date;

    int month = date.Month;

    while (date.Month == month && date.DayOfWeek != endOfWeek)
    {
        date = date.AddDays(1);
    }

    if (month != date.Month) date = date.AddDays(-1);

    return date;
}
  • Related