Home > Software engineering >  How to get the whole working week(Day's from Monday to Saturday), from our current date
How to get the whole working week(Day's from Monday to Saturday), from our current date

Time:11-22

I need to get the current working week from our current day. Example:

22.11.2022(Tuesday) should return me the dates from 21.11.2022(Monday) - 26.11.2022(Saturday)

27.11.2022(Sunday) should return me the next week: 28.11.2022(Monday) - 03.12.2022(Saturday).

I found this stack overflow question, but in Java(Don't really understand, how to translate it to c#): Input-Date-12/02/2022

Hopefully this answers your query. Have a great day

CodePudding user response:

This is all you need:

(DateTime start, DateTime end) GetWorkingWeek(DateTime fromDate)
{
    var start = fromDate.Date.AddDays(1.0 - (int)fromDate.DayOfWeek);
    var end = start.AddDays(5.0);
    return (start: start, end: end);
}

Now, from your sample input:

DateTime[] fromDates = new[]
{ 
    new DateTime(2022, 11, 22),
    new DateTime(2022, 11, 27),
};

(DateTime start, DateTime end)[] workingWeeks =
    fromDates
        .Select(GetWorkingWeek)
        .ToArray();

That gives:

output

CodePudding user response:

For me this works pretty well. It gives a list of the working days of the week

public List<DateTime> GetWorkingDaysOfWeek(DateTime date)
{
    List<DateTime> workingDays = new List<DateTime>();
    date = date.AddDays(-(date.Date.DayOfWeek.GetHashCode() - 1));

    for (int i = 0; i < 7; i  )
    {
        workingDays.Add(date.AddDays(i));
    }
    return workingDays;
}
  • Related