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;
}
}
{
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;
}
}