9

Goals

I have a list of LocalDate items that represent sets of start dates and end dates.

I would like to be able to store date ranges, so that I can perform operations on them as a set of overlapping or distinct ranges, etc.

Questions

  • Does NodaTime provide some sort of DateRange construct that I've missed in the docs?
  • Am I thinking about this wrong? Is there a more natural / preferred way to accomplish this that NodaTime already allows for?
  • Am I setting myself up for trouble by attempting to think about a date range using a LocalDate for a start and an end date?

I'm completely new to NodaTime and assuming that this is a conceptual misunderstanding on my part.

Update: I noticed a similar question on the subject from 2009, but that seems to refer to another utilies class; I'm assuming that since then NodaTime may have evolved to accomodate this situation.

4

1 回答 1

16

Noda Time 为Interval一系列Instant值提供类型,但不为其他类型提供范围类型。造成这种情况的部分原因是范围如何用于不同类型的细微差别。

如果我给你一个瞬间范围,它总是被视为半开区间。包括起始值,但不包括结束。每当我们提供时间值时,人类自然会这样做,例如当我说事件从1:00to运行时2:00,显然我的意思是事件2:00 结束,因此不包括 2:00。

但是对于整个日历日期范围,通常结束日期包括在内。为了代表一月份的整个月份(作为一个LocalDate值范围),我可能会说从 1 月 1 日到 1 月 31 日,并且我包括最后一天。

我们可能可以添加一些额外的范围类型来强制执行这些事情,但是当您可能只根据需要创建它们时,我们需要考虑在 API 中拥有它们有多少价值。无论哪种方式,我都不是说我赞成或反对,但这可能是野田时间用户组争论的话题。

要回答您的具体问题:

  • 不,本地日期没有预定义的范围类。
  • 唯一要考虑的另一件事是日历数学通常是通过Period课堂完成的。例如,要确定两个日历日期之间有多少天:

    LocalDate ld1 = new LocalDate(2012, 1, 1);
    LocalDate ld2 = new LocalDate(2013, 12, 25);
    Period period = Period.Between(ld1, ld2, PeriodUnits.Days);
    long days = period.Days;
    
  • 不,创建本地日期的范围类没有任何问题,只是可能没有很多优势。您可以通过在自己的类上拥有两个属性StartDate和来做同样的事情。EndDate请注意结束日期的包含性,以及您在间隔或时间范围内看到的排他性。

最后,你说:

...这样我就可以将它们作为一组重叠或不同的范围等执行操作。

您可能正在寻找诸如交集、联合、计算间隙、排序等操作。这些以及更多由Time Period Library定义,但 Noda Time 目前没有类似的东西。如果要创建它,它可能应该在一个配套库中(也许是“NodaTime.Ranges”?)。可能不希望将其拉入核心,但你永远不知道......

如果您最终使用了该时间段库,请确保您认识到它DateTime仅适用于DateTimeKind. 因此,为了提高工作效率,您可能应该确保您只使用 UTC 值或“未指定”日历日期,并尽量不要问“一天有多少小时”之类的问题,因为它会得到夏令时转换的日子是错误的。

于 2013-12-15T23:55:15.050 回答