Home > Software engineering >  Current week Monday is printed
Current week Monday is printed

Time:08-01

How can I set to C# property that day is automatically printed as Monday of current week?

public DateTime MondayOfCurrentWeek(this DateTime dt) 
{
    var today = DateTime.Now;
    return new GregorianCalendar().AddDays(today, -((int)today.DayOfWeek)   1);
}

Console.WriteLine($"Document date - {Document.MondayOfCurrentWeek(DateTime.Now)}");

CodePudding user response:

You can use DayOfWeek property of DateTime. Following function would work:

DateTime MondayOfCurrentWeek()
{
    int DaysToMonday(DayOfWeek dayOfWeek) => dayOfWeek switch
    {
        DayOfWeek.Monday => 0,
        DayOfWeek.Tuesday => -1,
        DayOfWeek.Wednesday => -2,
        DayOfWeek.Thursday => -3,
        DayOfWeek.Friday => -4,
        DayOfWeek.Saturday => -5,
        DayOfWeek.Sunday => -6
    };

    var now = DateTime.Now;
    var mondayOfCurrentWeek = now.AddDays(DaysToMonday(now.DayOfWeek));

    return mondayOfCurrentWeek;
}

CodePudding user response:

The problem you see is that the default "start of the week" is Sunday. I.e. DayOfWeek.Sunday is 0 while DayOfWeek.Monday is 1. So in your case, when var today = DateTime.Now is a Sunday, today.DayOfWeek will return 0;

If you want a less hard-coded way to get the date for the start of the week, you can do something like this:

public DateTime StartOfWeek(
    DateTime dt,
    DayOfWeek weekStart = DayOfWeek.Monday) 
{
    const int totalWeekDays = 7;
    var daysSinceWeekStart = (totalWeekDays - ((int)weekStart - (int)dt.DayOfWeek)) % totalWeekDays;
    return dt.AddDays(-daysSinceWeekStart);
}

// Use it like this:
Console.WriteLine($"Document date - {Document.StartOfWeek(DateTime.Now)}");

// Or, if you want Sunday to be the start of the week:
Console.WriteLine($"Document date - {Document.StartOfWeek(DateTime.Now, DayOfWeek.Sunday)}");
  •  Tags:  
  • c#
  • Related