减去2个日期

时间:2011-11-15 15:54:44

标签: c# .net

我需要能够减去2个日期并找回2之间的年份和月份。

有没有人知道有什么简单的方法可以做到这一点?

我查看了减去日期时返回的TimeSpan,但没有'NumberOfYears'等选项!

编辑:

我找到了以下文章

http://www.codeproject.com/KB/datetime/TimePeriod.aspx?msg=4078849#xx4078849xx

太棒了!

5 个答案:

答案 0 :(得分:3)

你可以从时间开始(不是时间的开始,但01/01/0001)取下滴答声:

// Assuming date 1 is the later date
DateTime newDate = new DateTime(myDate1.Ticks - myDate2.Ticks);

// NOTE : you might need to take 1 off each property, as they start at 1
string.Format("{0} Years, {1} Months, {2} Days", newDate.Year, newDate.Month, newDate.Day);

您可以创建一个模块,为您完成工作,它将循环计算日期之间的年数,直到年份相等或者在前一个月更大的情况下年份减去一年。然后你可以循环直到月份相等而不忘记从12下降到1。

int yearCount = 0;
int monthCount = 0;
int earliestYear = 0;
int earliestMonth = 0;
int latestYear = 0;
int latestMonth = 0;

// Get the earlier date, assuming that you haven't calculated which date is the latter already.
if (myDate1 > myDate2)
{
   earliestYear = myDate2.Year;
   earliestMonth = myDate2.Month;
}
else
{
   latestYear = myDate1.Year;
   latestMonth = myDate1.Month;
}

// Get the years between (remember not to include a year where the earlier dates month is greater than the latter. E.g. 09/2011 -> 01/2013 will only be 1 year, not 2!
while(earliestYear < latestYear && (earliestMonth <= latestMonth || earliestYear < (latestYear - 1)))
{
   yearCount++;
   earliestYear++;
}

// Finally get the months between, moving back to january after december.
while (earliestMonth != latestMonth)
{
   monthCount++;

   if (earliestMonth == 12)
   {
      earliestMonth = 1;
   }
   else
   {
      earliestMonth++;
   }
}

string.Format("{0} years and {1} months", yearCount, monthCount);

这是未经考虑的动态编写的代码,可为您提供一个粗略的想法。

这也假设您代表两个日期之间有1个月,例如29/02/1988和01/03/1988(英国日期时间格式)

你可以尝试使用一个时间跨度来完成任务,没有办法在没有一点手动代码的情况下获得这些年份虽然我确信你可以想出那个部分:-)(例如{{1}之类的东西})

days / 365.25

答案 1 :(得分:1)

答案 2 :(得分:0)

为什么不在DateTime上创建一个返回Tuple<int, int>或自定义类来满足您需求的扩展方法?特别是因为TimeSpan不能很好地满足您的需求,因为您需要计算从几天到几个月和几年(并考虑每个月的长度。)

public static Tuple<int, int> GetYearsAndMonthsDifference(this DateTime dt1, DateTime dt2)
{
    DateTime laterDate;
    DateTime earlierDate;

    if (dt1 > dt2)
    {
        earlierDate = dt2;
        laterDate = dt1;
    }
    else
    {
        earlierDate = dt1;
        laterDate = dt2;
    }

    int months = 0;

    while(earlierDate.Month != laterDate.Month || earlierDate.Year != laterDate.Year)
    {
        months++;
        earlierDate = earlierDate.AddMonths(1);
    }

    return Tuple.Create<int, int>(months / 12, months % 12);
}

用法:

var dt1 = DateTime.Now;
var dt2 = new DateTime(2010, 1, 1);

var difference = dt1.GetYearsAndMonthsDifference(dt2);

Console.WriteLine(string.Format("Years: {0}", difference.Item1));
Console.WriteLine(string.Format("Months: {0}", difference.Item2));

NB:如果你不喜欢Item1Item2那么你总是可以创建一个更好的自定义结构/类并返回它,而不是{{1 }}

答案 3 :(得分:0)

您可以使用刻度线创建一个DateTime。

DateTime tmp = new DateTime(date1.Ticks - date2.Ticks);
Console.WriteLine(tmp.Year - 1);
Console.WriteLine(tmp.Month - 1);
Console.WriteLine(tmp.Day - 1);

您必须从所有内容中减去1,因为1/1/1是第一个可能的日期,而不是0/0/0

答案 4 :(得分:0)

我找到的最佳解决方案是此代码项目文章:

http://www.codeproject.com/KB/datetime/TimePeriod.aspx?msg=4078849#xx4078849xx