IClock 1.1.0
Use System.TimeProvider instead (https://learn.microsoft.com/en-us/dotnet/api/system.timeprovider)
dotnet add package IClock --version 1.1.0
NuGet\Install-Package IClock -Version 1.1.0
<PackageReference Include="IClock" Version="1.1.0" />
paket add IClock --version 1.1.0
#r "nuget: IClock, 1.1.0"
// Install IClock as a Cake Addin #addin nuget:?package=IClock&version=1.1.0 // Install IClock as a Cake Tool #tool nuget:?package=IClock&version=1.1.0
<img src="https://raw.githubusercontent.com/RobThree/IClock/master/logo.png" alt="Logo" width="32" height="32"> IClock
Provides a testable abstraction and alternative to DateTime.Now
/ DateTime.UtcNow
and DateTimeOffset.Now
/ DateTimeOffset.UtcNow
. Targets netstandard1.0 and higher.
<a href="https://www.nuget.org/packages/IClock/"><img src="http://img.shields.io/nuget/v/IClock.svg?style=flat-square" alt="NuGet version" height="18"></a>
First: Good news! 🎉
As of the release of .Net 8 (nov. 14th 2023) Microsoft provides the TimeProvider class and ITimer interface. A good primer on this topic is over at Andrew Lock's site (archived version). You may want to check that out before continuing. What that means for IClock? It'll most likely be the end of this library, but that's a good thing. I'll keep supporting it for a while but switching to the Microsoft provided solution shouldn't be too hard.
Why and how
When writing and testing (date)time-related code it is tempting to use any of the DateTime.Now
, DateTime.UtcNow
, DateTimeOffset.Now
or DateTimeOffset.UtcNow
properties. This, however, causes problems during (unit)testing. It makes your tests dependent on when your tests are run. This means your tests could pass on tuesdays and, without any changes, fail on wednesdays. Or only fail during nighttime or at any other time.
Consider how you would test the following code:
public string Greet()
{
if (DateTime.Now.Hour < 12)
return "Good morning!";
else
return "Have a great day!";
}
Using DateTime.Now.Hour
is problematic here. What you really want is a clock that you can change at any time without any consequences and without having to change system time. This library provides interfaces and classes to handle just that. The TestClock
is the clock which you can change freely without consequences to your system.
The basis for this library is the ITimeProvider
interface which defines just one method: GetTime()
. All "Clock" classes in this library implement this interface. Each of the clocks is described below. For all your code that requires (date)time information, make sure you use the ITimeProvider
(or IScopedTimeProvider
, see the ScopedClock
for more information). Then, you can use one of the clocks (like the LocalClock
or UtcClock
) in your code and the TestClock
in your unittests.
Quickstart
In your code:
public class MyClass
{
private readonly ITimeProvider _timeprovider;
public MyClass(ITimeProvider timeProvider)
{
_timeprovider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
}
public void Foo()
{
// Instead of writing:
// var time = DateTime.Now;
// Use:
var time = _timeprovider.GetTime();
// Do something
}
}
var myclass = new MyClass(new UtcClock());
myClass.Foo();
//...
Or, even better, using Dependency Injection:
public void ConfigureServices(IServiceCollection services)
{
// Register UtcClock as timeprovider
services.AddScoped<ITimeProvider, UtcClock>();
// ...
}
For usage in unittests, see the TestClock
below.
DateTimeOffset vs DateTime
IClock provides DateTimeOffset
instead of DateTime
. Why? Read this excellent answer on StackOverflow (archived version).
DateTimeOffset
is great, however there are use-cases where you need to use DateTime
as Local or UTC in which case you can use the DateTimeOffset.LocalDateTime
and DateTimeOffset.UtcDateTime
properties.
LocalClock and UtcClock
These are the simplest ITimeProvider
s. They provide, as their name suggests, the system's Local or UTC time.
Example
var utctp = new UtcClock();
Console.WriteLine(utctp.GetTime());
var localtp = new LocalClock();
Console.WriteLine(localtp.GetTime());
ScopedClock
This clock takes a 'snapshot' of the time when it is created and 'freezes' time during it's lifetime. This can be handy in cases where you need the same time during, for example, handling a request or transaction.
The ScopedClock
takes either an ITimeProvider
, Func<DateTimeOffset>
or DateTimeOffset
as constructor argument. The time from the provider, function or literal at the time of the ScopedClock
's construction will be the time the ScopedClock
will provide when GetTime()
is called.
Example
public void ConfigureServices(IServiceCollection services)
{
// Register UtcClock as timeprovider
services.AddScoped<ITimeProvider, UtcClock>();
// Register ScopedClock as scoped timeprovider
services.AddScoped<IScopedTimeProvider, ScopedClock>();
// ...
}
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
private readonly ILogger<MyController> _logger;
private readonly ITimeProvider _timeprovider;
public MyController(ILogger<MyController> logger, IScopedTimeProvider timeProvider)
{
_logger = logger;
_timeprovider = timeProvider;
}
[HttpGet]
public string Get()
{
var time = _timeprovider.GetTime();
// Do stuff... whenever GetTime() is called again in any class that uses
// the same IScopedTimeProvider the same exact (date)time will be returned
}
}
ForwardOnlyClock
This clock is mostly a wrapper. It takes any ITimeProvider
and ensures that time always 'moves forward'. This means that, for example, during DST changes time will appear to stand still while the time 'catches up' to the point at which the DST timechange happened. This can be of use for, as the example mentioned, DST changes but also for timesources (or ITimeProviders
) that don't provide linear time.
Example
var tc = new TestClock();
var fc = new ForwardOnlyClock(tc);
Console.WriteLine(fc.GetTime()); // Show time
tc.Adjust(TimeSpan.FromHours(-1)); // Set clock back 1 hour
Console.WriteLine(fc.GetTime()); // Show time, should be same as previous
CustomClock
A simple wrapper ITimeProvider
that takes a Func<DateTimeOffset>
which it will then use whenever GetTime()
is invoked. This can be used in situations where you already have a function that returns time but you need it as an ITimeProvider
.
Example
// Assume we have a GPS receiver that returns the time from the GPS signal and we need it as an `ITimeSource`.
var gpsclock = new CustomClock(() => MyGpsReceiver.CurrentTime);
Console.WriteLine(gpsclock.GetTime()); // Show time
TestClock
This clock is primarily intended for use in unittesting scenarios and is the main reason for the existance of this library. See the 'Why and how' above. It can be initialized to any value (or it's default value of 2013-12-11 10:09:08.007+6:00
) and will only change when instructed. It has some conveniencemethods like Set()
(set to a specific time), Adjust()
(add/subtract time) and Tick()
(advance time with a variable increment).
Example
[TestMethod]
public void MyTest()
{
var tc = new TestClock(new DateTime(1999, 12, 31, 21, 00, 00));
var target = new PartyPlanner(tc); // Pass our timeprovider
Assert.IsTrue(target.IsPartyLike1999());
tc.Adjust(TimeSpan.FromHours(4)); // Set clock ahead 4 hours
Assert.IsFalse(target.IsPartyLike1999());
}
The TestClock
provides a static method (GetDeterministicRandomTime
, with an overload) that returns a (pseudo)random (date)time based on the caller method name (or a user supplied string) so tests that need to be repeatable (but maybe don't require a specific (date)time) can use this method of generating a (pseudo)random (date)time that is consistent over separate runs of the tests.
[TestMethod]
public void MyTest()
{
var time = TestClock.GetDeterministicRandomTime(); // Returns 2004-07-02T18:10:46.2105328+00:00
}
[TestMethod]
public void AnotherTest()
{
var time = TestClock.GetDeterministicRandomTime(); // Returns 1976-05-10T11:38:53.3889904+00:00
}
License
Licensed under MIT license. See LICENSE for details.
Attribution
Icon made by srip from www.flaticon.com. Inspired by dennisroche/DateTimeProvider, Melchy/Clock and rbwestmoreland/system.clock amongst others.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp1.0 was computed. netcoreapp1.1 was computed. netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard1.0 is compatible. netstandard1.1 was computed. netstandard1.2 was computed. netstandard1.3 was computed. netstandard1.4 was computed. netstandard1.5 was computed. netstandard1.6 was computed. netstandard2.0 was computed. netstandard2.1 was computed. |
.NET Framework | net45 was computed. net451 was computed. net452 was computed. net46 was computed. net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen30 was computed. tizen40 was computed. tizen60 was computed. |
Universal Windows Platform | uap was computed. uap10.0 was computed. |
Windows Phone | wp8 was computed. wp81 was computed. wpa81 was computed. |
Windows Store | netcore was computed. netcore45 was computed. netcore451 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 1.0
- NETStandard.Library (>= 1.6.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated | |
---|---|---|---|
1.1.0 | 7,086 | 11/20/2023 | |
1.0.1 | 36,519 | 9/3/2020 | |
1.0.0 | 444 | 9/3/2020 | |
1.0.0-alpha | 345 | 9/2/2020 |