// 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; using System.Globalization; namespace E { public static class MyExtensions { // ISO week number private static int WeekNum(int year, int mon, int day) { int a = (14 - mon) / 12; int y = year + 4800 - a; int m = mon + 12*a - 3; int JD = day + (153 * m + 2)/5 + 365*y + y/4 - y/100 + y/400 - 32045; int d4 = (((JD + 31741 - JD % 7) % 146097) % 36524) % 1461; int L = d4 / 1460; int d1 = ((d4 - L) % 365) + L; return d1 / 7 + 1; } public static int GetWeekNum(this DateTime dt) { return WeekNum(dt.Year, dt.Month, dt.Day); } } public class Program { public static bool IsSameWeek1(DateTime d1, DateTime d2) { CultureInfo ci = new CultureInfo("da-DK"); return ci.Calendar.GetWeekOfYear(d1, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday) == ci.Calendar.GetWeekOfYear(d2, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); } public static bool IsSameWeek2(DateTime d1, DateTime d2) { return d1.GetWeekNum() == d2.GetWeekNum(); } private static void Test(DateTime d1, DateTime d2) { Console.WriteLine("IsSameWeek1 - " + d1.ToString("dddd dd-MMM-yyyy") + " " + d2.ToString("dddd dd-MMM-yyyy") + " : " + IsSameWeek1(d1, d2)); Console.WriteLine("IsSameWeek2 - " + d1.ToString("dddd dd-MMM-yyyy") + " " + d2.ToString("dddd dd-MMM-yyyy") + " : " + IsSameWeek2(d1, d2)); } public static void Main(string[] args) { Test(DateTime.Now, new DateTime(2011, 5, 9)); Test(DateTime.Now, new DateTime(2011, 5, 6)); Test(new DateTime(2013, 1, 1), new DateTime(2012, 12, 31)); } } }