繁体   English   中英

在.net中找到两个时间戳之间的完整日历年,月,日和小时最容易浪费时间

[英]Easiest wasy to find full calendar years, months, days and hours between two time stamps in .net

我想做的如下

给定两个日期,例如1998年3月2日和2011年9月25日。如何将间隔分为

  1. 1998年3月2日至1998年3月31日(30天)
  2. 1998年4月1日至1998年12月31日(9个月)
  3. 1999年1月1日至2010年12月31日(11年)
  4. 2011年1月1日至2011年8月31日(8个月)
  5. 2011年9月1日至2011年9月25日(30天)

    但是,如果不存在任何间隔,则我们不希望强制包含该间隔,即结果将不会总是为天/月/年/年/月/天,例如

    给定开始日期='1998-02-01'和结束日期='2011-03-31',预期结果是(月/年/月)

    1998-02-01 ==> 1998-12-31 1999-01-01 ==> 2010-12-31 2011-01-01 ==> 2011-03-31

    给定开始日期='1998-02-01'和结束日期='1998-03-31',预期结果是(2个月)

    1998-02-01 ==> 2011-03-31

    给定开始日期='1998-01-05'和结束日期='1998-02-03',预期结果为(天/天)
    1998-01-05 ==> 2011-01-31 1998-02-01 ==> 2011-02-03

如果我的描述没有意义,请看以下内容。 我正在尝试实现相同的功能,但是在.net中

在任意时间范围内找到最佳的日/月/年间隔的算法?

您可以这样做:

DateTime startDate = new DateTime(1998, 3, 2);
DateTime endDate = new DateTime(2011, 9, 25);

DateTime firstMonth = new DateTime(startDate.Year, startDate.Month, 1).AddMonths(1);
DateTime firstYear = new DateTime(startDate.Year + 1, 1, 1);
DateTime lastYear = new DateTime(endDate.Year, 1, 1);
DateTime lastMonth = new DateTime(endDate.Year, endDate.Month, 1);

Console.WriteLine("{0:yyyy-MM-dd} - {1:yyyy-MM-dd}", startDate, firstMonth.AddDays(-1));
Console.WriteLine("{0:yyyy-MM-dd} - {1:yyyy-MM-dd}", firstMonth, firstYear.AddDays(-1));
Console.WriteLine("{0:yyyy-MM-dd} - {1:yyyy-MM-dd}", firstYear, lastYear.AddDays(-1));
Console.WriteLine("{0:yyyy-MM-dd} - {1:yyyy-MM-dd}", lastYear, lastMonth.AddDays(-1));
Console.WriteLine("{0:yyyy-MM-dd} - {1:yyyy-MM-dd}", lastMonth, endDate);

输出:

1998-03-02 - 1998-03-31
1998-04-01 - 1998-12-31
1999-01-01 - 2010-12-31
2011-01-01 - 2011-08-31
2011-09-01 - 2011-09-25

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM