Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 以年和月为单位获取持续时间_C#_Date - Fatal编程技术网

C# 以年和月为单位获取持续时间

C# 以年和月为单位获取持续时间,c#,date,C#,Date,我有两个日期:2011-07-05和2013-10-05 我如何以以下格式获取持续时间:2年3个月。最好的方法是什么? 我可以为此创建任何扩展方法或新类吗?请建议?任何帮助都将不胜感激 到目前为止,我已经做到了: public static string GetDuration(DateTime date1, DateTime date2) { int oldMonth = date2.Month; while (oldMonth == date2.Month) {

我有两个日期:
2011-07-05
2013-10-05

我如何以以下格式获取持续时间:
2年3个月
。最好的方法是什么? 我可以为此创建任何扩展方法或新类吗?请建议?任何帮助都将不胜感激

到目前为止,我已经做到了:

 public static string GetDuration(DateTime date1, DateTime date2) {
    int oldMonth = date2.Month;
    while (oldMonth == date2.Month) {
        date1 = date1.AddDays(-1);
        date2 = date2.AddDays(-1);
    }

    int years = 0, months = 0;

    // getting number of years
    while (date2.CompareTo(date1) >= 0) {
        years++;
        date2 = date2.AddYears(-1);
    }
    date2 = date2.AddYears(1);
    years--;

    // getting number of months and days
    oldMonth = date2.Month;
    while (date2.CompareTo(date1) >= 0) {
        date2 = date2.AddDays(-1);
        if ((date2.CompareTo(date1) >= 0) && (oldMonth != date2.Month)) {
            months++;
            oldMonth = date2.Month;
        }
    }

    return 
        "Difference: " +
        years.ToString() + " years" +
        ", " + months.ToString() + " months";
}

您可以看到实际情况。

不必过多考虑实际日期,这里有一个快速解决方案

int year, month;

if(date2.Month >= date1.Month)
{
  years = date2.Year - date1.Year;
  months = date2.Month - date1.Month;
}
else
{
  years = date2.Year - date1.Year - 1;
  months= date2.Month + 12 - date1.Month;
}

var duration=(Date1-Date2).ToString(“yyyy-MM”)
谢谢,但是
ToString()上有一个错误。
没有重载方法“ToString”需要1个参数非常感谢您的帮助
public static string GetDuration(DateTime date1, DateTime date2) 
{       
    var period = date2.AddDays(1) - date1;
    var date = new DateTime(period.Ticks);
    var totalYears = date.Year - 1;
    var totalMonths = ((date.Year - 1) * 12) + date.Month - 1;
    var extraMonths = totalMonths - (totalYears * 12);

    return string.Format("{0} years {1} months", totalYears, extraMonths);
}
int year, month;

if(date2.Month >= date1.Month)
{
  years = date2.Year - date1.Year;
  months = date2.Month - date1.Month;
}
else
{
  years = date2.Year - date1.Year - 1;
  months= date2.Month + 12 - date1.Month;
}