Skip to content

mattjohnsonpint/NodaTime.NetworkClock

Repository files navigation

NodaTime.NetworkClock NuGet Version

A NodaTime.IClock implementation that gets the current time from an NTP server instead of the computer's local clock.

Installation

PM> Install-Package NodaTime.NetworkClock

This library is targeting .NET Standard 1.3.
See the .NET Standard Platform Support Matrix for further details.

Example Usage

// Just like SystemClock, you can obtain a singleton instance
var clock = NetworkClock.Instance;

// Optionally, you can adjust some settings.
// These are the defaults, and can be omited if you aren't going to change them.
clock.NtpServer = "pool.ntp.org";              // which server to contact
clock.CacheTimeout = Duration.FromMinutes(15); // how long between calls to the server

// Call .GetCurrentInstant() to get the current time as an Instant
Instant now = clock.GetCurrentInstant();

// Like any Instant, you can then convert to a time zone
DateTimeZone tz = DateTimeZoneProviders.Tzdb["America/New_York"];
ZonedDateTime zdt = now.InZone(tz);

// Of course, you can convert this to whatever format makes sense in your application.
// You can use any of the following:
LocalDateTime ldt = zdt.LocalDateTime;
OffsetDateTime odt = zdt.ToOffsetDateTime();
DateTimeOffset dto = zdt.ToDateTimeOffset();
DateTime dt = zdt.ToDateTimeUnspecified();
// Alternatively, you can create a ZonedClock for a specific time zone
var tz = DateTimeZoneProviders.Tzdb["Australia/Lord_Howe"];
var clock = new ZonedClock(NetworkClock.Instance, tz);

// This makes it easy to reason about current time in a particular location
ZonedDateTime zdt = clock.GetCurrentZonedDateTime();
OffsetDateTime odt = clock.GetCurrentOffsetDateTime();
LocalDateTime ldt = clock.GetCurrentLocalDateTime();
LocalDate ld = clock.GetCurrentDate();
LocalTime lt = clock.GetCurrentTimeOfDay();

Notes

Note that technically, the implementation is currently just "SNTP", as it doesn't account for the delay in retrieving the time, and it only makes a single query to the server. I will probably update it to a full NTP client at some point. (PR's are welcome!)