2011-09-30 30 views
37

Duplicar posibles:
ASP.net get the next tuesday¿Cómo obtener la fecha del próximo domingo?

Dado un día del mes, ¿cómo puedo obtener el próximo domingo a partir de ese día?

Así que si paso el martes 13 de septiembre de 2011, volverá el 18 de septiembre.

+5

leer la propiedad 'DayOfWeek'. Calcula cuántos días antes del domingo es esto. Llamar a 'AddDays' pasando ese número. –

+0

¿Es un ejercicio de tarea? De ser así, marque la pregunta con la etiqueta 'tarea' –

+1

¿Qué ocurre si solo tengo un bucle e incremente el día y compruebe si es el día deseado? romper si es. – codecompleting

Respuesta

74

utilizo este método de extensión:

public static DateTime Next(this DateTime from, DayOfWeek dayOfWeek) 
    { 
     int start = (int)from.DayOfWeek; 
     int target = (int)dayOfWeek; 
     if (target <= start) 
      target += 7; 
     return from.AddDays(target - start); 
    } 
+0

¿No está usando los valores subyacentes de un Enum peligroso? –

+3

+1 por lo que es un método de extensión –

+5

@Spencer K: Depende, en caso de días de la semana, me sorprendería mucho que cambiaría en el futuro cercano (o incluso lejano) ;-) –

3
/// <summary> 
/// Finds the next date whose day of the week equals the specified day of the week. 
/// </summary> 
/// <param name="startDate"> 
/// The date to begin the search. 
/// </param> 
/// <param name="desiredDay"> 
/// The desired day of the week whose date will be returneed. 
/// </param> 
/// <returns> 
/// The returned date is on the given day of this week. 
/// If the given day is before given date, the date for the 
/// following week's desired day is returned. 
/// </returns> 
public static DateTime GetNextDateForDay(DateTime startDate, DayOfWeek desiredDay) 
{ 
    // (There has to be a better way to do this, perhaps mathematically.) 
    // Traverse this week 
    DateTime nextDate = startDate; 
    while(nextDate.DayOfWeek != desiredDay) 
     nextDate = nextDate.AddDays(1D); 

    return nextDate; 
} 

Fuente:

http://angstrey.com/index.php/2009/04/25/finding-the-next-date-for-day-of-week/

23

date.AddDays(7 - (int)date.DayOfWeek) debe hacerlo creo.

date.DayOfWeek devolverá un valor enum que representa el día (donde 0 es domingo).

+0

Hice una pequeña modificación que funcionó bien para mí. DateTime.Today.AddDays (7 - (int) DayOfWeek.Saturday) .ToShortDateString() – dvdmn

+7

Dvdnhm cuidadoso, que solo agrega 1 día a la fecha de hoy. – Joey

+0

gracias por su preocupación, funcionó bien para mi propósito y usándolo en el proyecto .. – dvdmn

5
 var date = DateTime.Now; 
     var nextSunday = date.AddDays(7 - (int) date.DayOfWeek);  

Si necesita más cercana Domingo, código poco diferente (como si estás en Domingo, domingo más cercano se encuentra en la actualidad):

var nearestSunday = date.AddDays(7 - date.DayOfWeek == DayOfWeek.Sunday ? 7 : date.DayOfWeek); 
2

Aquí está el código:

int dayOfWeek = (int) DateTime.Now.DayOfWeek; 
DateTime nextSunday = DateTime.Now.AddDays(7 - dayOfWeek).Date; 

Obtenga primero el valor numérico del día de la semana, en su ejemplo: martes = 2

Luego reste del domingo, 7 -2 = 5 días para agregar para obtener la fecha del próximo domingo. :)

0
DateTime dt=dateTime; 
do { 
    dt=dt.AddDays(1); 
} while(dt.DayOfWeek!= DayOfWeek.Sunday); 
// 'dt' is now the next Sunday 

Su pregunta no está clara si se devuelve la misma fecha si la fecha ya es un domingo; Supongo que no, pero cambie lo anterior a un ciclo while si estoy equivocado.

0

Ejemplo utilizando la recursividad

private static DateTime GetNextSunday(DateTime dt) 
    { 
     var tomorrow = dt.AddDays(1); 
     if (tomorrow.DayOfWeek != DayOfWeek.Sunday) 
     { 
      GetNextSunday(tomorrow); 
     } 

     return tomorrow; 
    } 
+2

¿Desea comentar al usuario infractor? Odio cuando la gente hace eso ... –

+0

¡Odiaría eso también! Sin embargo, creo que esto no funcionaría bien. Como se mencionó, las instancias de DateTime son inmutables y ni siquiera usa el valor de retorno de su método. Otra cosa para mencionar: es realmente agradable poner este tipo de funcionalidad en los métodos de extensión, al menos para mi gusto. – Kjellski

0
public static DateTime GetNextSunday (DateTime date) 
{ 
    if (date.DayOfWeek == DayOfWeek.Sunday) 
      date = date.AddDays(1); 
    while (date.DayOfWeek != DayOfWeek.Sunday) 
      date = date.AddDays(1); 

    return date; 
} 
+0

Agregas 1 día sin importar el día actual ... – Joey

+0

Agrego 1 día si es actualmente el domingo (supongo que si es domingo, el OP quiere el próximo domingo), entonces sigue agregando días hasta que sea Domingo. Entonces regresa ese día. A menos que me esté perdiendo algo. – MattW

Cuestiones relacionadas