如何在c#中计算两个日期之间的月差?

c#中是否有相当于VB的DateDiff()方法。我需要找出相隔数年的两个日期之间的月差。文档说我可以像这样使用TimeSpan:

TimeSpan ts = date1 - date2;

但这里的数据是以天为单位的。我不想把这个数字除以30,因为不是每个月都是30天,而且两个操作数的值相差很大,所以我担心除以30可能会得到错误的值。

有什么建议吗?


当前回答

以下是我对获得Months差异的贡献,我发现这是准确的:

namespace System
{
     public static class DateTimeExtensions
     {
         public static Int32 DiffMonths( this DateTime start, DateTime end )
         {
             Int32 months = 0;
             DateTime tmp = start;

             while ( tmp < end )
             {
                 months++;
                 tmp = tmp.AddMonths( 1 );
             }

             return months;
        }
    }
}

用法:

Int32 months = DateTime.Now.DiffMonths( DateTime.Now.AddYears( 5 ) );

您可以创建另一个名为DiffYears的方法,并应用与上面完全相同的逻辑,并在while循环中使用AddYears而不是AddMonths。

其他回答

要获得月份的差异(包括开始和结束),而不考虑日期:

DateTime start = new DateTime(2013, 1, 1);
DateTime end = new DateTime(2014, 2, 1);
var diffMonths = (end.Month + end.Year * 12) - (start.Month + start.Year * 12);

LINQ的解决方案,

DateTime ToDate = DateTime.Today;
DateTime FromDate = ToDate.Date.AddYears(-1).AddDays(1);

int monthCount = Enumerable.Range(0, 1 + ToDate.Subtract(FromDate).Days)
                    .Select(x => FromDate.AddDays(x))
                    .ToList<DateTime>()
                    .GroupBy(z => new { z.Year, z.Month })
                    .Count();

一定是有人干的))

扩展方法返回给定日期之间的完整月数。无论以什么顺序接收日期,都会返回一个自然数。在“正确”答案中没有近似的计算。

    /// <summary>
    /// Returns the difference between dates in months.
    /// </summary>
    /// <param name="current">First considered date.</param>
    /// <param name="another">Second considered date.</param>
    /// <returns>The number of full months between the given dates.</returns>
    public static int DifferenceInMonths(this DateTime current, DateTime another)
    {
        DateTime previous, next;
        if (current > another)
        {
            previous = another;
            next     = current;
        }
        else
        {
            previous = current;
            next     = another;
        }

        return
            (next.Year - previous.Year) * 12     // multiply the difference in years by 12 months
          + next.Month - previous.Month          // add difference in months
          + (previous.Day <= next.Day ? 0 : -1); // if the day of the next date has not reached the day of the previous one, then the last month has not yet ended
    }

但如果你仍然想要得到月份的小数部分,你只需要在回报中再加一项:

+(下一个。Day - previous.Day) / DateTime.DaysInMonth(previous. Day)年,previous.Month)

这是对Kirk Woll的回答的回应。我还没有足够的声望点来回复评论……

我喜欢Kirk的解决方案,并打算无耻地窃取它并在我的代码中使用它,但当我仔细查看它时,我意识到它太复杂了。不必要的切换和循环,以及使用毫无意义的公共构造函数。

以下是我的改写:

public class DateTimeSpan {
    private DateTime _date1;
    private DateTime _date2;
    private int _years;
    private int _months;
    private int _days;
    private int _hours;
    private int _minutes;
    private int _seconds;
    private int _milliseconds;

    public int Years { get { return _years; } }
    public int Months { get { return _months; } }
    public int Days { get { return _days; } }
    public int Hours { get { return _hours; } }
    public int Minutes { get { return _minutes; } }
    public int Seconds { get { return _seconds; } }
    public int Milliseconds { get { return _milliseconds; } }

    public DateTimeSpan(DateTime date1, DateTime date2) {
        _date1 = (date1 > date2) ? date1 : date2;
        _date2 = (date2 < date1) ? date2 : date1;

        _years = _date1.Year - _date2.Year;
        _months = (_years * 12) + _date1.Month - _date2.Month;
        TimeSpan t = (_date2 - _date1);
        _days = t.Days;
        _hours = t.Hours;
        _minutes = t.Minutes;
        _seconds = t.Seconds;
        _milliseconds = t.Milliseconds;

    }

    public static DateTimeSpan CompareDates(DateTime date1, DateTime date2) {
        return new DateTimeSpan(date1, date2);
    }
}

用法1,基本相同:

void Main()
{
    DateTime compareTo = DateTime.Parse("8/13/2010 8:33:21 AM");
    DateTime now = DateTime.Parse("2/9/2012 10:10:11 AM");
    var dateSpan = new DateTimeSpan(compareTo, now);
    Console.WriteLine("Years: " + dateSpan.Years);
    Console.WriteLine("Months: " + dateSpan.Months);
    Console.WriteLine("Days: " + dateSpan.Days);
    Console.WriteLine("Hours: " + dateSpan.Hours);
    Console.WriteLine("Minutes: " + dateSpan.Minutes);
    Console.WriteLine("Seconds: " + dateSpan.Seconds);
    Console.WriteLine("Milliseconds: " + dateSpan.Milliseconds);
}

Usage2类似:

void Main()
{
    DateTime compareTo = DateTime.Parse("8/13/2010 8:33:21 AM");
    DateTime now = DateTime.Parse("2/9/2012 10:10:11 AM");
    Console.WriteLine("Years: " + DateTimeSpan.CompareDates(compareTo, now).Years);
    Console.WriteLine("Months: " + DateTimeSpan.CompareDates(compareTo, now).Months);
    Console.WriteLine("Days: " + DateTimeSpan.CompareDates(compareTo, now).Days);
    Console.WriteLine("Hours: " + DateTimeSpan.CompareDates(compareTo, now).Hours);
    Console.WriteLine("Minutes: " + DateTimeSpan.CompareDates(compareTo, now).Minutes);
    Console.WriteLine("Seconds: " + DateTimeSpan.CompareDates(compareTo, now).Seconds);
    Console.WriteLine("Milliseconds: " + DateTimeSpan.CompareDates(compareTo, now).Milliseconds);
}

似乎DateTimeSpan解决方案使许多人满意。我不知道。让我们考虑一下:

BeginDate = 1972/2/29销售= 1972/4/28。

基于DateTimeSpan的答案是:

1年(s), 2个月(s)和0天(s)

我实现了一个方法,在此基础上,答案是:

1年、1个月及28天

显然没有两个月的时间。我想说的是,因为我们在开始日期的月末,剩下的实际上是整个3月加上结束日期(4月)的月份所经过的天数,所以1个月零28天。

如果你读到这里,你有兴趣,我把方法贴在下面。我在评论中解释了我所做的假设,因为有多少个月,月份的概念是一个不断变化的目标。多次测试,看看答案是否有意义。我通常选择相邻年份的考试日期,一旦我确认了答案,我就会前后移动一两天。到目前为止,它看起来不错,我相信你会发现一些bug:D。代码可能看起来有点粗糙,但我希望它足够清楚:

static void Main(string[] args) {
        DateTime EndDate = new DateTime(1973, 4, 28);
        DateTime BeginDate = new DateTime(1972, 2, 29);
        int years, months, days;
        GetYearsMonthsDays(EndDate, BeginDate, out years, out months, out days);
        Console.WriteLine($"{years} year(s), {months} month(s) and {days} day(s)");
    }

    /// <summary>
    /// Calculates how many years, months and days are between two dates.
    /// </summary>
    /// <remarks>
    /// The fundamental idea here is that most of the time all of us agree
    /// that a month has passed today since the same day of the previous month.
    /// A particular case is when both days are the last days of their respective months 
    /// when again we can say one month has passed.
    /// In the following cases the idea of a month is a moving target.
    /// - When only the beginning date is the last day of the month then we're left just with 
    /// a number of days from the next month equal to the day of the month that end date represent
    /// - When only the end date is the last day of its respective month we clearly have a 
    /// whole month plus a few days after the the day of the beginning date until the end of its
    /// respective months
    /// In all the other cases we'll check
    /// - beginingDay > endDay -> less then a month just daysToEndofBeginingMonth + dayofTheEndMonth
    /// - beginingDay < endDay -> full month + (endDay - beginingDay)
    /// - beginingDay == endDay -> one full month 0 days
    /// 
    /// </remarks>
    /// 
    private static void GetYearsMonthsDays(DateTime EndDate, DateTime BeginDate, out int years, out int months, out int days ) {
        var beginMonthDays = DateTime.DaysInMonth(BeginDate.Year, BeginDate.Month);
        var endMonthDays = DateTime.DaysInMonth(EndDate.Year, EndDate.Month);
        // get the full years
        years = EndDate.Year - BeginDate.Year - 1;
        // how many full months in the first year
        var firstYearMonths = 12 - BeginDate.Month;
        // how many full months in the last year
        var endYearMonths = EndDate.Month - 1;
        // full months
        months = firstYearMonths + endYearMonths;           
        days = 0;
        // Particular end of month cases
        if(beginMonthDays == BeginDate.Day && endMonthDays == EndDate.Day) {
            months++;
        }
        else if(beginMonthDays == BeginDate.Day) {
            days += EndDate.Day;
        }
        else if(endMonthDays == EndDate.Day) {
            days += beginMonthDays - BeginDate.Day;
        }
        // For all the other cases
        else if(EndDate.Day > BeginDate.Day) {
            months++;
            days += EndDate.Day - BeginDate.Day;
        }
        else if(EndDate.Day < BeginDate.Day) {                
            days += beginMonthDays - BeginDate.Day;
            days += EndDate.Day;
        }
        else {
            months++;
        }
        if(months >= 12) {
            years++;
            months = months - 12;
        }
    }