Date difference in years using C#

This question already has an answer here:

  • How do I calculate someone's age in C#? 64 answers

  • I have written an implementation that properly works with dates exactly one year apart.

    However, it does not gracefully handle negative timespans, unlike the other algorithm. It also doesn't use its own date arithmetic, instead relying upon the standard library for that.

    So without further ado, here is the code:

    DateTime zeroTime = new DateTime(1, 1, 1);
    
    DateTime a = new DateTime(2007, 1, 1);
    DateTime b = new DateTime(2008, 1, 1);
    
    TimeSpan span = b - a;
    // Because we start at year 1 for the Gregorian
    // calendar, we must subtract a year here.
    int years = (zeroTime + span).Year - 1;
    
    // 1, where my other algorithm resulted in 0.
    Console.WriteLine("Yrs elapsed: " + years);
    

    使用:

    int Years(DateTime start, DateTime end)
    {
        return (end.Year - start.Year - 1) +
            (((end.Month > start.Month) ||
            ((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0);
    }
    

    We had to code a check to establish if the difference between two dates, a start and end date was greater than 2 years.

    Thanks to the tips above it was done as follows:

     DateTime StartDate = Convert.ToDateTime("01/01/2012");
     DateTime EndDate = Convert.ToDateTime("01/01/2014");
     DateTime TwoYears = StartDate.AddYears(2);
    
     if EndDate > TwoYears .....
    
    链接地址: http://www.djcxy.com/p/54346.html

    上一篇: 如何根据生日来计算年龄?

    下一篇: 使用C#的日期差异