Duplicata possible : ASP.net obtient le mardi prochain
Étant donné un jour du mois, comment puis-je obtenir le dimanche suivant à partir de ce jour ?
Donc si je passe le mardi 13 septembre 2011, il reviendra le 18 septembre.
Réponses
Trop de publicités?
Joey
Points
1150
Giedrius
Points
3765
var date = DateTime.Now;
var nextSunday = date.AddDays(7 - (int) date.DayOfWeek);
Si vous avez besoin du dimanche le plus proche, codez un peu différemment (comme si vous étiez le dimanche, le dimanche le plus proche est aujourd'hui) :
var nearestSunday = date.AddDays(7 - date.DayOfWeek == DayOfWeek.Sunday ? 7 : date.DayOfWeek);
Jason Quinn
Points
1318
/// <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;
}
La source:
http://angstrey.com/index.php/2009/04/25/finding-the-next-date-for-day-of-week/
Bryan Hong
Points
1127
Voici le code :
int dayOfWeek = (int) DateTime.Now.DayOfWeek;
DateTime nextSunday = DateTime.Now.AddDays(7 - dayOfWeek).Date;
Obtenez d'abord la valeur numérique du jour de la semaine, dans votre exemple : mardi = 2
Ensuite, soustrayez-le du dimanche, 7 -2 = 5 jours à ajouter pour obtenir la date du dimanche suivant. :)