如何使用NodaTime检查“现在”是否在两个OffsetDateTime对象之间?

问题描述

我需要设置这种视图模型的IsCurrent字段:

public class SessionVm {
    public OffsetDateTime StartTime { get; set; }
    public OffsetDateTime EndTime { get; set; }
    public string TimezoneId { get; set; }
    public bool IsCurrent {get;}
}

我认为我可以为IsCurrent字段编写这样的getter:

public bool IsCurrent
{
    get
    {
        var currentTimeWithOffset = new OffsetDateTime(LocalDateTime.FromDateTime(DateTime.UtcNow),StartTime.Offset);
        return StartTime < currentTimeWithOffset && currentTimeWithOffset < EndTime;
    }
}

但是,看来OffsetDateTime没有实现IComparable。然后,我发现LocalDateTime可以并尝试了此操作:

public bool IsCurrent
{
    get
    {
        var currentLocalDateTime = SystemClock.Instance.InUtc().GetCurrentLocalDateTime();
        var currentOffsetDateTime = new OffsetDateTime(currentLocalDateTime,StartTime.Offset);
        var currentLocalDateTimeExpectedWithOffsetAdded = currentOffsetDateTime.LocalDateTime;

        var startLocalDateTime = StartTime.LocalDateTime;
        var endLocalDateTime = StartTime.LocalDateTime;
        return startLocalDateTime < currentLocalDateTimeExpectedWithOffsetAdded && currentLocalDateTimeExpectedWithOffsetAdded < endLocalDateTime;
    }
}

但是,currentLocalDateTimeExpectedWithOffsetAdded并不能真正代表我的需求。在OffsetDateTime字段上方的LocalDateTime类文档中:

/// <summary>
/// Returns the local date and time represented within this offset date and time.
/// </summary>
/// <value>The local date and time represented within this offset date and time.</value>
public LocalDateTime LocalDateTime => new LocalDateTime(Date,TimeOfDay);

显然,我对这句话有误解,并认为这会使我的日期时间有偏差。
您能帮我弄清楚如何获取添加了偏移量的UTC日期时间对象吗?还是有更好的方法来实现IsCurrent字段? 预先谢谢你:)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)