Csharp/C#教程:Noda Time – 带区域的开始/结束日期分享


Noda Time – 带区域的开始/结束日期

在代码运行的系统上设置的时区中,获取ZonedDateTime(表示当前日期的开始和结束)的正确和更简洁的方法是什么?

以下代码是不是太复杂了?

ZonedDateTime nowInZone = SystemClock.Instance.Now.InZone(DateTimeZoneProviders.Bcl.GetSystemDefault()); ZonedDateTime start = new LocalDateTime(nowInZone.Year, nowInZone.Month, nowInZone.Day, 0, 0, 0).InZoneStrictly(DateTimeZoneProviders.Bcl.GetSystemDefault()); ZonedDateTime end = new LocalDateTime(nowInZone.Year, nowInZone.Month, nowInZone.Day, 23, 59, 59).InZoneStrictly(DateTimeZoneProviders.Bcl.GetSystemDefault()); 

鉴于这些值,我需要测试另一个ZonedDateTime是否在它们之间。

DateTimeZone对象上的AtStartOfDay值具有您正在寻找的魔力。

 // Get the current time IClock systemClock = SystemClock.Instance; Instant now = systemClock.Now; // Get the local time zone, and the current date DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault(); LocalDate today = now.InZone(tz).Date; // Get the start of the day, and the start of the next day as the end date ZonedDateTime dayStart = tz.AtStartOfDay(today); ZonedDateTime dayEnd = tz.AtStartOfDay(today.PlusDays(1)); // Compare instants using inclusive start and exclusive end ZonedDateTime other = new ZonedDateTime(); // some other value bool between = dayStart.ToInstant() <= other.ToInstant() && dayEnd.ToInstant() > other.ToInstant(); 

几点:

更新

正如Jon在评论中提到的, Interval类型可能是一个有用的便利。 它已经设置为使用半开放的Instant值范围。 以下函数将获取特定时区中当前“日期”的间隔:

 public Interval GetTodaysInterval(IClock clock, DateTimeZone timeZone) { LocalDate today = clock.Now.InZone(timeZone).Date; ZonedDateTime dayStart = timeZone.AtStartOfDay(today); ZonedDateTime dayEnd = timeZone.AtStartOfDay(today.PlusDays(1)); return new Interval(dayStart.ToInstant(), dayEnd.ToInstant()); } 

像这样调用它(使用上面相同的值):

 Interval day = GetTodaysInterval(systemClock, tz); 

现在可以使用Contains函数进行比较:

 bool between = day.Contains(other.ToInstant()); 

请注意,您仍然必须转换为Instant ,因为Interval类型不能Interval时区。

上述就是C#学习教程:Noda Time – 带区域的开始/结束日期分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1003415.html

(0)
上一篇 2021年12月28日
下一篇 2021年12月28日

精彩推荐