我有一个方法应该返回一个工作日的开始时间,例如9AM来自ZonedDateTime,它作为参数:
public ZonedDateTime GetWorkStartTime(ZonedDateTime zdt) => (zdt.Zone.AtStartOfDay(zdt.Date).Date + WorkDayStartTime).InZone(zdt.Zone, CommonLenientResolver);
WorkDayStartTime
是new 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。
答案 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);
假设您的解析器按照您希望的方式处理跳过/不明确值的所有内容,那应该没问题。