首页 文章

计算C#中两个日期之间的年,月和日[重复]

提问于
浏览
1

这个问题在这里已有答案:

我想要在两个日期之间经过确切的年,月和日 .

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

DateTime endDate = DateTime.Now.ToLocalTime();

我想找到使用C#的上述两天之间经过的年数,月数和天数?

我的预期产出年份:68个月:10天:23

我推荐了一篇帖子,因为他们只解释了几天Calculate difference between two dates (number of days)?

但我需要三年,一年,一天和一天 . 请帮助我如何计算......

Explanation for Duplicate :已经在Calculate Years, Months, weeks and Days中发布了相同逻辑的问题,该问题中提供的答案过于冗长且 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 ,我在这里以非常简单的方式得到了答案 . I satisfied in my answer .

Exact Duplicate:

原始问题:How to get difference between two dates in Year/Month/Week/Day?Asked 7 Years ago

你的标记问题:Calculate Years, Months, weeks and DaysAsked 5 Years ago

1 回答

  • 5

    有趣的问题:

    解决方案是

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

相关问题