Calculate Year, Month and Day between two Dates in C#

user6060080 picture user6060080 · Jul 6, 2016 · Viewed 13.1k times · Source

I want exact Year, Month and Day elapsed between two dates.

DateTime startDate = new DateTime(1974, 8, 15);

DateTime endDate = DateTime.Now.ToLocalTime();

I wish to find Number of Years, Months and Days elapsed between the above two days using C#?

My Expected Output

Years: 68 Months: 10 Days: 23

I referred one of the post, in that they explained about only days Calculate difference between two dates (number of days)?

But I need all three - Year, Month and Day. Kindly assist me how to calculate...

Explanation for Duplicate: Already a question with same logic posted in Calculate Years, Months, weeks and Days, the answer provided in that question is too lengthy and in my question I asked only Year, Month and Date not Week. The Concept is same but the logic is different for calculating days comparing to that question, Here I got the answer in a very simplified manner. I satisfied in my answer.

Exact Duplicate:

Original Question: How to get difference between two dates in Year/Month/Week/Day? (Asked 7 Years ago)

Your Marked Question: Calculate Years, Months, weeks and Days (Asked 5 Years ago)

Answer

B.Balamanigandan picture B.Balamanigandan · Jul 6, 2016

Interesting Question:

The Solution is

void Main()
{
    DateTime zeroTime = new DateTime(1, 1, 1);
    DateTime olddate = new DateTime(1947, 8,15);
    olddate.Dump();
    DateTime curdate = DateTime.Now.ToLocalTime();
    curdate.Dump();

    TimeSpan span = curdate - olddate;

    // because we start at year 1 for the Gregorian 
    // calendar, we must subtract a year here.

    int years = (zeroTime + span).Year - 1;
    int months = (zeroTime + span).Month - 1;
    int days = (zeroTime + span).Day;

    years.Dump();
    months.Dump();
    days.Dump();
}