C#获取两个DateTime日期之间的差异

本文关键字:之间 日期 DateTime 两个 获取 | 更新日期: 2023-09-27 18:03:48

所以我正在开发一个具有日期功能的小应用程序(显示天、月、年等的差异(现在,像"选择的日期是14151天、465个月和39年前"这样的事情很容易,但我如何才能用可读的格式("15天、7个月和三十九年前"(来表达呢?

现在要做到这一点,我已经准备好在像这样的年份里获得差异

int years = selectedDate.Year - currentDate.Year

几个月和几天都一样。然而,这几乎不起作用,而且会出错,尤其是在一个月后(可能会说15天和1个月,因为date1.Day-date2.Day=15,而实际上可能是,比如8天。我认为这是因为日期与月份n的关系,但我不确定。

不管怎样,我希望我说得有道理,因为我甚至无法真正跟踪自己。任何想法都非常感谢D

C#获取两个DateTime日期之间的差异

从一个DateTime减去另一个返回TimeSpan,您可以使用它来确定两个日期之间的时间段,表示为天、小时、分钟、秒等的时间度量。

TimeSpan result = selectedDate - currentDate;
result.Days...
result.Hours...
etc.

获取月份和年份更为棘手,因为一个月中的天数每年都会变化等等。你必须手动计算,也许是在原始DateTime对象之外。

在短时间内,您可以这样做:

        TimeSpan timeDiff = selectedDate - currentDate;
        string readableDiff = string.Format(
            "{0:D2} hrs, {1:D2} mins, {2:D2} secs",
            timeDiff.Hours, timeDiff.Minutes, timeDiff.Seconds);

但我注意到,你正在处理涉及数年甚至数月的较长时期。对于这样的计算,你需要比TimeSpan更强大的东西。您可以查看Jon Skeet的用于.NET平台的Noda Time端口:https://code.google.com/p/noda-time/

有了Noda Time,你可以做这样的事情:

        var period = Period.Between(selectedDate, currentDate,
            PeriodUnits.Years | PeriodUnits.Months | PeriodUnits.Days);
        string readableDifference = string.Format(
            "{0} years, {1} months and {2} days",
            period.Years, period.Months, period.Days);

您可以使用DateTime类进行数学运算。结果是TimeSpan,其行为类似于DateTime,只是表示时间长度而不是绝对日期。

DateTime selectedDate;
DateTime currentDate;
TimeSpan difference = selectedDate.Subtract(currentDate);
string result = difference.ToString("whatever format you like");

使用TimeSpanMath.Abs来说明负值:

DateTime date1 = new DateTime(2012, 5, 15);
DateTime date2 = new DateTime(2014, 5, 16);
TimeSpan dateDiff = date1 - date2;
int years = Math.Abs((int)dateDiff.TotalDays) / 365;

我这样做是为了获得两个月日期之间的差异:

var start = startDate.Value;
var end = endDate.Value;
var duration = ((end.Year - start.Year) * 12) + end.Month - start.Month;

当然,我得到的唯一原因是。值是因为它们是可以为null的日期,但我想你可以在你的情况下使用类似的东西。

如果取两个DateTime对象之间的差,则得到一个TimeSpan对象。

DateTime a = DateTime.Now;
DateTime b = DateTime.Now.AddYears(-1);
TimeSpan c = a - b;
Console.WriteLine( c );

将得到364.23:59:59.9951930的答案。您可以为格式化的响应重载toString((,也可以根据需要获得c.TotalMilliseconds并除以/模,以获得多少年/月/等等。。。