使用NodaTime计算一个包容性天期 [英] use NodaTime to calculate an inclusive days period
问题描述
因此,举例来说,如果我有以下代码:
VAR nodaStart =新LOCALDATE(2012,5,1);
变种nodaEnd =新LOCALDATE(2012,5,2);
VAR daysBetween = Period.Between(nodaStart,nodaEnd,PeriodUnits.Day);
然后 daysBetween.Days == 1
不过,我计算的需求范围,计为2天。也就是说,它需要具有包容性的开始和结束日期。
实际的方法可以采取,并开始和结束日期(即不超过一年的除外)和需求来计算天数。如果有超过31天,那么其余的都返回了一些整个星期。
我有逻辑,工作正常,但因为计数是专属我算是一天。
我想我可以做 startDate.addDays(-1)
创建之前 nodaStart
,但我不知道是否有有野田回报周期更优雅/美丽的方式。
感谢
更新:
我已经的为周期
类的源代码和在 +
运算符重载,所以我可以添加
daysBetween + =周期.FromDays(1);
(对不起,这是我花这么长时间来回答这个问题 - 我从来没有见过吧)
的任何的的:
- 添加一天结束计算之前(这是最符合逻辑的做法,IMO - 罗杰说,你要在第二天开始,有效的)
- 减去开始新一天计算
- 前加入1至你走出月底的天数
应该罚款。我不认为野田佳彦时间会改变,使这个再简单不过。 之间
是一种周围的单位模糊的减法运算符的版本 - 你不会找到很多减法运算,其中2 - 1是2
So for example if I have the following code:
var nodaStart = new LocalDate(2012, 5, 1);
var nodaEnd = new LocalDate(2012,5,2);
var daysBetween = Period.Between(nodaStart, nodaEnd,PeriodUnits.Day);
Then daysBetween.Days == 1
However, the range I calculate needs to count that as 2 days. i.e. it needs to be inclusive of the start and end date.
The actual method can take and start and end date (that are no more than a year apart) and needs to calculate the number of days. If there are more than 31 days then the remainder are returned as a number of whole weeks.
I have that logic working fine but because the count is exclusive I'm one day out.
I guess I can just do startDate.addDays(-1)
before I create nodaStart
from it but I wonder if there's a more elegant / pretty way to have noda return the Period.
Thanks
UPDATE:
I've had a read of the source code for the Period
class and the +
operator is overloaded so I can add
daysBetween += Period.FromDays(1);
(Sorry it's taken me so long to answer this - I hadn't seen it before.)
Any of:
- Adding a day to the end before calculating (this is the most logical approach, IMO - as Roger says, you want the start of the next day, effectively)
- Subtracting a day from the start before calculating
- Adding 1 to the number of days you get out of the end
should be fine. I don't think Noda Time will change to make this any simpler. Between
is a sort of "fuzzy around units" version of a subtraction operator - and you won't find many subtraction operators where 2 - 1 is 2.
这篇关于使用NodaTime计算一个包容性天期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!