如何正确地在Nodatime中设置ZonedDateTime的时间组件

时间:2016-01-08 16:09:41

标签: c# .net nodatime

我有一个方法应该返回一个工作日的开始时间,例如9AM来自ZonedDateTime,它作为参数:

public ZonedDateTime GetWorkStartTime(ZonedDateTime zdt) => (zdt.Zone.AtStartOfDay(zdt.Date).Date + WorkDayStartTime).InZone(zdt.Zone, CommonLenientResolver);

WorkDayStartTimenew LocalTime(9, 0)

CommonLenientResolver是自定义解析程序,请参阅Comparing LocalDateTime for Different Time Zones in Nodatime

处的实施

因此,对于任何特定的zdt,我都希望确保返回值始终是zdt参数所代表的当天的9AM。

正如AtStartOfDay(...)的文档中所述,如果时钟变化不存在的一天午夜(例如时钟在午夜直到凌晨1点向前移动),Nodatime将自动使用下一个可用实例,1AM。 在我目前的实现中,我向AtStartOfDay(...)添加了9个小时,因此如果当天的开始时间是凌晨1点,我的GetWorkStartTime(...)将返回10AM,这就是我所说的。我想避免。

我正在使用Nodatime 1.3.1。

1 个答案:

答案 0 :(得分:2)

听起来您根本不需要使用AtStartOfDay - 只需使用日期并添加WorkDayStartTime

public ZonedDateTime GetWorkStartTime(ZonedDateTime zdt) =>
    (zdt.Date + WorkDayStartTime).InZone(zdt.Zone, CommonLenientResolver);

或者如果你发现它更清楚:

public ZonedDateTime GetWorkStartTime(ZonedDateTime zdt) =>
    zdt.Date.At(WorkDayStartTime).InZone(zdt.Zone, CommonLenientResolver);

假设您的解析器按照您希望的方式处理跳过/不明确值的所有内容,那应该没问题。