Get year Difference between two date 获取两个日期相差几年

class Program
    {
        static void Main(string[] args)
        {
            string date = "2011-08-15";
            DateTime d0 = DateTime.Parse(date);
            Console.WriteLine(d0.ToString("D0 IS : yyyy-MM"));
            DateTime d1 = DateTime.Now;
            Console.WriteLine(d1.ToString("D1 IS : yyyy-MM"));

            int r = GetDateDiffYears(d0,d1);
            Console.WriteLine(r.ToString());
            Console.Read();
        }

        /// <summary>
        
/// Get Difference between two date
        
/// 获取两个日期的时间差
        
/// </summary>
        
/// <param name="d0">start date</param>
        
/// <param name="d1">end date</param>
        
/// <returns></returns>
        static int GetDateDiffYears(DateTime d0,DateTime d1)
        {
            int y = d1.Year - d0.Year;
            int m = d1.Month - d0.Month;
            int d = d1.Day - d0.Day;
            if (d > 0)
                m++;
            if (d < 0)
                m--;
            int r = y * 12 + m;
            if (r % 12 == 0)
            {
                r = r / 12;
            }
            else
            {
                r = r / 12 + 1;
            }
            return r;
        }
    }
posted @ 2012-08-16 10:57  zyip  阅读(374)  评论(0编辑  收藏  举报