Fecha y hora: obtener el próximo martes

¿Cómo puedo obtener la fecha del próximo martes?

En PHP, es tan simple como strtotime('next tuesday'); .

¿Cómo puedo lograr algo similar en .NET

Como mencioné en los comentarios, hay varias cosas que podría querer decir con “el próximo martes”, pero este código le indica “el próximo martes ocurrirá, o hoy si ya es martes”:

 DateTime today = DateTime.Today; // The (... + 7) % 7 ensures we end up with a value in the range [0, 6] int daysUntilTuesday = ((int) DayOfWeek.Tuesday - (int) today.DayOfWeek + 7) % 7; DateTime nextTuesday = today.AddDays(daysUntilTuesday); 

Si desea dar “una semana” si ya es martes, puede usar:

 // This finds the next Monday (or today if it's Monday) and then adds a day... so the // result is in the range [1-7] int daysUntilTuesday = (((int) DayOfWeek.Monday - (int) today.DayOfWeek + 7) % 7) + 1; 

… o podría usar la fórmula original, pero a partir de mañana:

 DateTime tomorrow = DateTime.Today.AddDays(1); // The (... + 7) % 7 ensures we end up with a value in the range [0, 6] int daysUntilTuesday = ((int) DayOfWeek.Tuesday - (int) tomorrow.DayOfWeek + 7) % 7; DateTime nextTuesday = tomorrow.AddDays(daysUntilTuesday); 

EDITAR: solo para que esto sea agradable y versátil:

 public static DateTime GetNextWeekday(DateTime start, DayOfWeek day) { // The (... + 7) % 7 ensures we end up with a value in the range [0, 6] int daysToAdd = ((int) day - (int) start.DayOfWeek + 7) % 7; return start.AddDays(daysToAdd); } 

Entonces, para obtener el valor de “hoy o en los próximos 6 días”:

 DateTime nextTuesday = GetNextWeekday(DateTime.Today, DayOfWeek.Tuesday); 

Para obtener el valor para “el próximo martes excluyendo hoy”:

 DateTime nextTuesday = GetNextWeekday(DateTime.Today.AddDays(1), DayOfWeek.Tuesday); 

Esto debería funcionar:

 static DateTime GetNextWeekday(DayOfWeek day) { DateTime result = DateTime.Now.AddDays(1); while( result.DayOfWeek != day ) result = result.AddDays(1); return result; } 
 DateTime nextTuesday = DateTime.Today.AddDays(((int)DateTime.Today.DayOfWeek - (int)DayOfWeek.Tuesday) + 7); 

Hay soluciones menos detalladas y más inteligentes / elegantes para este problema, pero la siguiente función C # funciona muy bien para una serie de situaciones.

 ///  /// Find the closest weekday to the given date ///  /// if the supplied date is on the specified day of the week, return that date or continue to the next date /// search forward or backward from the supplied date. if a null parameter is given, the closest weekday (ie in either direction) is returned public static DateTime ClosestWeekDay(this DateTime date, DayOfWeek weekday, bool includeStartDate = true, bool? searchForward=true) { if (!searchForward.HasValue && !includeStartDate) { throw new ArgumentException("if searching in both directions, start date must be a valid result"); } var day = date.DayOfWeek; int add = ((int)weekday - (int)day); if (searchForward.HasValue) { if (add < 0 && searchForward.Value) { add += 7; } else if (add > 0 && !searchForward.Value) { add -= 7; } else if (add == 0 && !includeStartDate) { add = searchForward.Value ? 7 : -7; } } else if (add < -3) { add += 7; } else if (add > 3) { add -= 7; } return date.AddDays(add); } 
 DateTime nexttuesday=DateTime.Today.AddDays(1); while(nexttuesday.DayOfWeek!=DayOfWeek.Tuesday) nexttuesday = nexttuesday.AddDays(1); 

@Jon Skeet buena respuesta.

Para el día anterior:

 private DateTime GetPrevWeekday(DateTime start, DayOfWeek day) { // The (... - 7) % 7 ensures we end up with a value in the range [0, 6] int daysToRemove = ((int) day - (int) start.DayOfWeek - 7) % 7; return start.AddDays(daysToRemove); } 

¡¡Gracias!!

Ahora en sabor a lápiz de líneas, en caso de que necesites pasarlo como parámetro a algún mecanismo.

 DateTime.Now.AddDays(((int)yourDate.DayOfWeek - (int)DateTime.Now.DayOfWeek + 7) % 7).Day 

En este caso específico:

 DateTime.Now.AddDays(((int)DayOfWeek.Tuesday - (int)DateTime.Now.DayOfWeek + 7) % 7).Day 

Podría ser una extensión también, todo depende

 public static class DateTimeExtensions { public static IEnumerable Next(this DateTime date, DayOfWeek day) { // This loop feels expensive and useless, but the point is IEnumerable while(true) { if (date.DayOfWeek == day) { yield return date; } date = date.AddDays(1); } } } 

Uso

  var today = DateTime.Today; foreach(var monday in today.Next(DayOfWeek.Monday)) { Console.WriteLine(monday); Console.ReadKey(); } 

Versión Objetivo C:

 +(NSInteger) daysUntilNextWeekday: (NSDate*)startDate withTargetWeekday: (NSInteger) targetWeekday { NSInteger startWeekday = [[NSCalendar currentCalendar] component:NSCalendarUnitWeekday fromDate:startDate]; return (targetWeekday - startWeekday + 7) % 7; }