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(); 
}

你可能感兴趣的:(C#)