Set DateTimePicker start date always Monday C #

2

I am developing a Windows Forms application in C #. I have a DateTimePicker that I will call dtp1 .

It happens that what I need is that this dtp1 always have the date on Monday of the current week.

That is,

  • If today is Jueves 06/10/2016 , the value of this dtp1 should be 03/10/2016 .
  • If we start the program with Miércoles 12/10/2016 , it should show 10/10/2016 .
asked by Juan Manuel Villavicencio Tapi 07.10.2016 в 00:55
source

1 answer

3

Well, you can convert the dt to Monday and then set it on the dtpicker

Translation of How can I get the DateTime for the start of the week?

  

Use an extension method. They are the answer to everything, you know! ;)

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = dt.DayOfWeek - startOfWeek;
        if (diff < 0)
        {
            diff += 7;
        }
        return dt.AddDays(-1 * diff).Date;
    }
}
     

Which can be used as follows:

DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);//El que tu necesitas
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
    
answered by 07.10.2016 в 01:03