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

徘徊边缘 提交于 2021-02-10 04:43:20

问题


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)


回答1:


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();
}


来源:https://stackoverflow.com/questions/38215171/calculate-year-month-and-day-between-two-dates-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!