使用 NodaTime 如何将现在的本地时间与固定时间进行比较?

Using NodaTime how do I compare the local time now to a fixed time?

我希望能够使用 NodaTime 将 C# 中的当前本地时间与白天的固定本地时间进行比较。我不需要担心时区或夏令时,我只需要与本地系统时间进行比较。到目前为止我有这个代码...

IClock clock = SystemClock.Instance;
Instant instant = clock.Now;
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
var timeNow = zonedDateTime.ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture);
int tst = timeNow.CompareTo(new LocalTime(11, 00));
if (tst < 0)
{
    eventLog1.WriteEntry("Time is before 11am.");
}

我收到一个错误,但由于我是 C# 的新手,NodTime 希望能在我出错的地方提供一些指示。

要获取本地系统时间,您确实需要担心时区。您可以使用:

var clock = SystemClock.Instance; // Or inject it, preferrably
// Note that this *could* throw an exception. You could use
// DateTimeZoneProviders.Bcl.GetSystemDefault() to use the Windows
// time zone database.
var zone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
var now = clock.Now.InZone(zone);

if (now.TimeOfDay < new LocalTime(11, 0))
{
    ...
}

在 Noda Time 2.0 中,使用 ZonedClock:

var zonedClock = SystemClock.Instance.InTzdbSystemDefaultZone();
if (zonedClock.GetCurrentTimeOfDay() < new LocalTime(11, 0))
{
    ...
}

对于 "earlier than 11 o'clock",您当然可以始终使用 if (time.Hour < 11),但使用 LocalTime 更为通用。