DateTime - 1 week

7

I have the following variable:

  DateTime zonaSemana = DateTime.Today.AddDays(((int)DayOfWeek.Wednesday - (int)DateTime.Today.DayOfWeek) == 0 ? 7 : ((int)DayOfWeek.Wednesday - (int)DateTime.Today.DayOfWeek + 7) % 7).AddSeconds(1);

Is there any way to make it shorter? It is about me the date of the following Wednesday.

I mean I have the following:

This adds 10 min:

 zonaMins = DateTime.Now.AddMinutes(10);

This 24 hours:

   zonaDias = new DateTime(DateTime.Now.AddDays(1).Year, DateTime.Now.AddDays(1).Month, DateTime.Now.AddDays(1).Day, 0, 0, 1);

But the one week does not work well and I do not know the reason. He has to give me Wednesday and I do not know if it's because it's too long ... or something.

thanks

    
asked by Montse Mkd 31.08.2018 в 12:05
source

2 answers

7

Well, the problem is that if you execute the code the same day of the week that you are looking for, it does not give you the next Wednesday but the Wednesday in which you are already. That is easily solved by looking for the next Tuesday, instead of Wednesday, and adding one day. That is:

DateTime zonaSemana = DateTime.Today.AddDays((((int)DayOfWeek.Tuesday - (int)DateTime.Today.DayOfWeek + 7) % 7)+1 ).AddSeconds(1) ;
    
answered by 31.08.2018 / 12:39
source
6

What you can do is:

private DateTime calcularProxMiercoles()
{
    var day = DateTime.Today;
    do
    {
        day = day.AddDays(1);
    } while (day.DayOfWeek != DayOfWeek.Wednesday);
    return day;
}

This will always return to you next Wednesday (if today is Wednesday and you want me to return the same day change the do while for only the while ).

    
answered by 31.08.2018 в 12:30