c# - C#计算两个日期之间的年月日

标签 c# date date-difference

<分区>

我想要两个日期之间经过的确切年、月和日。

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

DateTime endDate = DateTime.Now.ToLocalTime();

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

My Expected Output

Years: 68 Months: 10 Days: 23

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

但我需要所有三个 - 年、月和日。请帮助我如何计算...

重复说明: 已经在 Calculate Years, Months, weeks and Days 中发布了具有相同逻辑的问题,该问题中提供的答案太长,而且在我的问题中我只问了年、月和日而不是周概念相同,但计算天数的逻辑与该问题相比不同,在这里我以非常简化的方式得到了答案。 我对自己的回答很满意

完全重复:

原始问题:How to get difference between two dates in Year/Month/Week/Day? (7 年前问)

您标记的问题:Calculate Years, Months, weeks and Days (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# - C#计算两个日期之间的年月日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38215171/

相关文章:

c# - Thread.VolatileRead()与Volatile.Read()

C# WPF : Getting Custom Binding Error (Converter Property Unknown) After Restoring Project from SourceSafe

date - 如何使用Elasticsearch从当前时间减去日期?

java - 如何计算提供两个日期的老化?

.net - 获取上周一的日期

javascript - Moment.js 两个日期之间的持续时间

c# - 三角形数的约数 (Euler 12)

c# - 拦截 NHibernate Lazy-Load 行为以在未连接到 session 时返回 null?

javascript - 如何在javascript中将日期转换为带有时区的UTC毫秒

python - 值错误 : time data does not match format when parsing a date