// 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; namespace E { public class MainClass { public struct YMD { public int Y; public int M; public int D; } public static YMD DateDiffBackward(DateTime t1, DateTime t2) { YMD res = new YMD(); DateTime tmp = t1; while(tmp.AddYears(-1) >= t2) { res.Y++; tmp = tmp.AddYears(-1); } while(tmp.AddMonths(-1) >= t2) { res.M++; tmp = tmp.AddMonths(-1); } while(tmp.AddDays(-1) >= t2) { res.D++; tmp = tmp.AddDays(-1); } return res; } public static YMD DateDiffForward(DateTime t1, DateTime t2) { YMD res = new YMD(); DateTime tmp = t2; while(tmp.AddYears(1) <= t1) { res.Y++; tmp = tmp.AddYears(1); } while(tmp.AddMonths(1) <= t1) { res.M++; tmp = tmp.AddMonths(1); } while(tmp.AddDays(1) <= t1) { res.D++; tmp = tmp.AddDays(1); } return res; } public static void Test(DateTime t1, DateTime t2) { Console.WriteLine(t1 + " " + t2); YMD d1 = DateDiffBackward(t1, t2); Console.WriteLine("Backward: " + d1.Y + " " + d1.M + " " + d1.D); YMD d2 = DateDiffForward(t1, t2); Console.WriteLine("Forward: " + d2.Y + " " + d2.M + " " + d2.D); } public static void Main(string[] args) { Test(new DateTime(2006, 8, 26), new DateTime(2004, 9, 25)); Test(new DateTime(2006, 8, 25), new DateTime(2004, 9, 26)); Test(new DateTime(2006, 2, 28), new DateTime(2004, 1, 30)); Test(new DateTime(2006, 3, 31), new DateTime(2004, 2, 28)); Console.ReadLine(); } } }