计算C#中两个日期之间的年,月和日 [英] Calculate Year, Month and Day between two Dates in C#

查看:158
本文介绍了计算C#中两个日期之间的年,月和日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在两个日期之间准确地经过年,月和日.

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

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

DateTime endDate = DateTime.Now.ToLocalTime();

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

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

我的预期输出

年份: 68 月: 10 天: 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.

完全相同:

原始问题:如何是否获得年/月/周/日的两个日期之间的差异?( 7年前询问)

您标记的问题:计算年,月,周和天(要求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();
}

这篇关于计算C#中两个日期之间的年,月和日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆