计算现在和下一个当地时间之间的持续时间

时间:2014-08-11 22:45:15

标签: nodatime

我需要确定从现在到下一次当地时间的持续时间。这就是我所拥有的:

Duration GetDuration(IClock clock, LocalTime time, DateTimeZone zone)
{
    // get the current time in this zone
    var now = clock.Now.InZone(zone);

    // find the time in our zone today
    var timeToday = zone.AtLeniently(now.Date + time);

    // find the time in our zone tomorrow
    var timeTomorrow = zone.AtLeniently(now.Date.PlusDays(1) + time);

    // get the next occurrance of that time
    var next = new[]{timeToday, timeTomorrow}.Where(x => x > now).Min();        

    // calculate the duration between now and the next occurance of that time
    var duration = next.ToInstant() - now.ToInstant();  
    Debug.Assert(duration > Duration.Zero);
    return duration;
}

从东部时间下午5点到现在和下一时刻之间的持续时间进行测试:

var duration = GetDuration(
    SystemClock.Instance,
    new LocalTime(17,00),
    DateTimeZoneProviders.Tzdb["US/Eastern"]);

我的问题是,既然我是NodaTime的新手,我是采取了不必要的步骤还是错过了任何捷径?

2 个答案:

答案 0 :(得分:3)

这段代码比我们需要的更啰嗦 - 我在" local"中完成大部分工作。上下文,只有在您知道要映射的LocalDateTime时才转换回时区。

var now = clock.Now.InZone(zone);
// Change this to <= time if you want it to be a "strictly next".
var nextDate = now.TimeOfDay < time ? now.Date : now.Date.PlusDays(1);

return zone.AtLeniently(nextDate + time).ToInstant() - now.ToInstant();

AtLeniently将始终返回一个之前的值而不是给定的LocalDateTime(它返回两个不明确的选项中的后一个,以及之后的间隔的开始)跳过时间),所以你不必担心DST过渡。

顺便说一句,关于最后一行ToInstant()调用是否令人讨厌的反馈会很有用。我至少考虑Duration operator-(ZonedDateTime, ZonedDateTime)添加到2.0。

答案 1 :(得分:0)

最简单的方法就是这样:

    LocalDate now = LocalDate.now();
    LocalDate now2 = now.plusDays(4);
    ChronoUnit.DAYS.between(now, now2);