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

I want to be able to compare the current local time in C# using NodaTime to a fixed local time during the day. I do not need to worry about time zones or daylight savings, I just need to do the comparison with the local system time. So far I have this code...

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.");
}

I get an error but as I am relatively new to C# and NodTime would appreciate some pointers where I am going wrong.

Jon Skeet
people
quotationmark

To get the local system time, you do need to worry about the time zone. You can use:

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))
{
    ...
}

In Noda Time 2.0, this is made somewhat simpler using ZonedClock:

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

For "earlier than 11 o'clock" you could always use if (time.Hour < 11) of course, but using a LocalTime is more general.

people

See more on this question at Stackoverflow