算上按日期时间覆盖包容的日期数 [英] Count the number of inclusive dates covered by a date period

查看:175
本文介绍了算上按日期时间覆盖包容的日期数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待计数的日期数两个 DateTime是否

这是不是 .TotalDays 为周期不超过24小时仍可能返回2重叠的两个不同天。同样,两个日期分钟,除了应该还是回到1

This is not .TotalDays as periods less than 24 hours may still return "2" by overlapping two different days. Likewise, two dates minutes apart should still return "1".

例如:

2012-2-1 14:00 to 2012-2-2 23:00 -> 2 (1st and 2nd Feb)
2012-2-1 14:00 to 2012-2-2 10:00 -> 2 (1st and 2nd Feb)
2012-2-1 23:00 to 2012-2-2 00:00 -> 2 (1st and 2nd Feb)
2012-2-1 23:00 to 2012-2-3 00:00 -> 3 (1st, 2nd, 3rd Feb)
2012-2-1 14:00 to 2012-2-1 15:00 -> 1 (1st Feb)
2012-2-1 14:00 to 2012-2-1 14:00 -> 1 (1st Feb)
2012-1-1 00:00 to 2012-12-31 23:59 -> 366 (All of 2012)



我可以用下面的代码此功能:

I can get this functionality with the code below:

DateTime dt1 = new DateTime(2000,1,2,12,00,00);
DateTime dt2 = new DateTime(2000,1,3,03,00,00);

int count = 0;
for (DateTime date = dt1; date.Date <= dt2.Date; date = date.AddDays(1))
    count++;

return count;



有没有更好的办法?

Is there a better way?

推荐答案

为什么不干脆:

int count = dt1.Date.Subtract(dt2.Date).Duration().Days + 1;

使用 .Date 标准化日期到午夜(0:00),加1 来得到不同的日期,不只是在之间的天数数。

Using .Date normalizes the Date to midnight (0:00), add 1 to the Days to get the number of different dates, not just the number of days in between.

使用持续时间确保您始终获得了肯定的回答。

Using Duration makes sure you always get a positive answer.

这篇关于算上按日期时间覆盖包容的日期数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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