Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no IDateTimeProvider in .NET and DateTime has Now getter?

Tags:

c#

.net

oop

Currently I'm writing a unit test for a component that does datetime specific validation. I have created IDateTimeProvider interface, that serves as a DateTime.UtcNow wraper and business objects use interface rather than DateTime directly. It seems that DateTime is a bit overloaded and should be split into a value and a thing that gets that value from the OS. I wonder if there is a particular reason not to have a IDateTimeProvider (IClock) interface in .NET?

like image 475
Kimi Avatar asked Jun 28 '10 10:06

Kimi


People also ask

What is the difference between DateTime now and DateTime today in C#?

DateTime. Today is DateTime. Now with time set to zero.

What does DateTime now return C#?

The Now property returns a DateTime value that represents the current date and time on the local computer.

How slow is DateTime now?

DateTime. Now is over 10X SLOWER than DateTime.

How can I get tomorrow date in C#?

Explanation: In the above example, first of all, we find tomorrow's date by adding today's date with the timespan of 1. Here, we get today's date using the DateTime. Now method.


2 Answers

Simply put: because large parts of the BCL weren't designed for testability.

The same is true for random number generation, in terms of "core" functionality - and a lot of the HTTP-related classes are much worse to fake out :( At least in this case it's reasonably easy to introduce your own clock interface.

On the plus side, when Noda Time is ready for production use, it will not only provide a better date/time API than the BCL - it'll provide a more test-friendly one :)

like image 123
Jon Skeet Avatar answered Sep 28 '22 22:09

Jon Skeet


We consistently use a DateTimeProvider wrapper class which we can override in a test context if necessary...

like image 40
Koen Avatar answered Sep 28 '22 21:09

Koen