C# 获取两个时间相差年月

public static string GetDateYAndM(string beginDate, string endDate)
{
  var bdate= Convert.ToDateTime(beginDate);
  var edate= Convert.ToDateTime(endDate);


  int years = -1;
  int months = -1;


  if (bdate> edate)
    return null;

  while (bdate<= edate)
  {
    bdate= bdate.AddYears(1);
    years++;
  }
  if (years < 2)
  {
    bdate= Convert.ToDateTime(beginDate);
    while (bdate<= edate)
    {
      bdate= bdate.AddMonths(1);
      months++;
    }
}
  return years.toString()+"-"+months.toString(); 
}

posted @ 2012-05-15 10:56  二姐1511  阅读(2273)  评论(0编辑  收藏  举报