// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; class MainClass { public static DateTime NextSunday(DateTime dt) { DateTime res = dt; do { res = res.AddDays(1); } while(res.DayOfWeek != DayOfWeek.Sunday); return res; } public static DateTime PrevSunday(DateTime dt) { DateTime res = dt; do { res = res.AddDays(-1); } while(res.DayOfWeek != DayOfWeek.Sunday); return res; } public static DateTime NearSunday(DateTime dt) { if(dt.DayOfWeek == DayOfWeek.Sunday) { return dt; } DateTime next = NextSunday(dt); DateTime prev = PrevSunday(dt); if(next - dt < dt - prev) { return next; } else { return prev; } } public static void Test(DateTime dt) { Console.WriteLine(dt.ToShortDateString() + " " + PrevSunday(dt).ToShortDateString() + " " + NextSunday(dt).ToShortDateString() + " " + NearSunday(dt).ToShortDateString()); } public static void Main(string[] args) { Test(DateTime.Parse("1-Mar-2005")); Test(DateTime.Parse("2-Mar-2005")); Test(DateTime.Parse("3-Mar-2005")); Test(DateTime.Parse("27-Feb-2005")); } }