年,月和日的2天之间的差异 [英] Difference between 2 days in years, months and days

查看:83
本文介绍了年,月和日的2天之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要输出年,月和日两天之间的差。

I need to output the difference between 2 days in years, months and days.

使用时间跨度和减法,我只能得到天数,但是可以输出年,月和日。

With timespan and subtract i only get the days but is it possible to output in years, months and days.

这是我到目前为止所拥有的:

This is what i have so far:

public string Leeftijdsverschil(DateTime p1, DateTime p2)
{
    if (p1 > p2)
    {
        DateTime verschil = p1.Subtract(TimeSpan.FromTicks(p2.Ticks));
        return verschil.ToString();
    }
    else
    {
        DateTime verschil = p2.Subtract(TimeSpan.FromTicks(p1.Ticks));
        return verschil.ToString();
    }
}


推荐答案

.NET类型无法为您提供一个不错的答案,而无需编写代码来尝试一个答案并进行适当调整,但是我的 Noda Time 项目旨在处理这种情况。例如:

The .NET types don't give you a decent answer to this without having to write code to try one answer and adjust appropriately, but my Noda Time project is designed to handle this sort of thing. For example:

LocalDate x = new LocalDate(2013, 5, 21);
LocalDate y = new LocalDate(2014, 12, 15);
Period p = Period.Between(x, y);
Console.WriteLine("{0} {1} {2}", p.Years, p.Months, p.Days);

结果:

1 6 24

(即1年,6个月和24天)

(i.e. 1 year, 6 months and 24 days)

如果您决定为此使用Noda Time,则可以使用 DateTime 在其他位置并在类型之间进行转换...但是通常最好更广泛地使用Noda Time。目的是使您的代码比使用 DateTime 更加清晰。

If you decide to use Noda Time for this, you could just do it within your method, using DateTime elsewhere and converting between the types... but it would generally be better to embrace Noda Time more widely. The aim is for it to allow your code to be clearer than just using DateTime.

这篇关于年,月和日的2天之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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