首页 文章

错误计算两个日期之间的年/月/日

提问于
浏览
1

我尝试做的是计算两个日期之间的年数,月数和天数 . 不幸的是,没有.NET Framework的方法可以做到这一点 .

我所做的基本上如下:http://www.codeproject.com/Articles/28837/Calculating-Duration-Between-Two-Dates-in-Years-Mo

根据所述网站的评论进行一些调整:

var monthDay = new[] { 31, 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

DayCalculation:

if (fromDate.Day > toDate.Day)
{
    increment = monthDay[toDate.Month - 1];
}

if (increment == -1)
{
    increment = DateTime.IsLeapYear(toDate.Year) ? 29 : 28;
}

所以我有以下效果:

日期1:1979-01-30

日期2:2013-03-01

输出为:34年,1个月,-1天

预期产量为:34年,1个月,1天

每次都会发生这种效果,Date2是3月的日期 .

你知道这个计算有什么问题吗?或者您是否知道如何获得理想结果的更好解决方案?

提前致谢

PS:我知道你可以计算两个日期之间的天数,但我需要的是成品年数,完成月数和完成天数

2 回答

  • 8

    不幸的是,没有.NET Framework的方法可以做到这一点 .

    是的,但是有Noda Time而不是:)(这是我对.NET的Joda Time的端口,尽管这两个项目之间存在很多差异 . )

    LocalDate start = new LocalDate(1979, 1, 30);
    LocalDate end = new LocalDate(2013, 3, 1);
    Period period = Period.Between(start, end);
    Console.WriteLine("{0} years, {1} months, {2} days",
                      period.Years, period.Months, period.Days);
    

    输出:

    34 years, 1 months, 1 days
    
  • 0

    这是一种在不使用外部库的情况下计算差异的方法 . 需要两个日期 . 我假设第一个日期不晚于第二个日期 . 否则,您必须交换它们才能使计算正确 .

    var first = new DateTime(1979, 1, 30);
    var second = new DateTime(2013, 3, 1);
    

    以下是计算差异的方法 . 您不需要表格来获取该月的天数 . 该信息由 DateTime.DaysInMonth 函数提供 .

    var years = second.Year - first.Year;
    var months = second.Month - first.Month;
    if (months < 0) {
      months += 12;
      years -= 1;
    }
    var days = second.Day - first.Day;
    if (days < 0) {
      var daysInFirstMonth = DateTime.DaysInMonth(first.Year, first.Month);
      days += daysInFirstMonth;
      months -= 1;
    }
    

    打印计算值

    Console.WriteLine("{0} year(s), {1} month(s), {2} day(s)", years, months, days);
    

    会导致

    34 year(s), 1 month(s), 2 day(s)
    

    这会产生与您链接的代码相同的结果 . 但是,您希望获得1天而不是2天 . 我想这取决于你如何定义"days between" . 如果您希望仅计算1月31日之间的日期,则可以从 days 中减去1 . 然后在两个相邻日期和-1天"between the same date"之间将有0天 .

相关问题