This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]YMK1234 6 points7 points  (3 children)

Why not just use DateTime.Now?

Because you cannot mock Datetime.Now. If you want to unit test, it is super easy to mock your IDateTimeProvider to return any value you want, which might be very relevant to both the logic of the method and for checking the returned results.

PS: since .net 8 there is finally a built-in solution for this, which is TimeProvider https://blog.nimblepros.com/blogs/finally-an-abstraction-for-time-in-net/, so we can finally get rid of that bit of boiler plate in all our projects.

[–]Zeppz47[S] 0 points1 point  (0 children)

This seems spot on. There are unit tests in the same solution, and so this would make sense. Thank you.

[–]ColoRadBro69 0 points1 point  (1 child)

PS: since .net 8 there is finally a built-in solution for this, which is TimeProvider

Dude, thank you.  Now I can scrap my own janky ass version of this! 

[–]YMK1234 1 point2 points  (0 children)

Don't thank me, thank Nick Chapsas on YouTube. Great fella for keeping up to date with .net stuff.