Saturday, April 11, 2015

Manage a mix of both DateTime.Now and DateTime.UtcNow as an external dependency.

It's easy to put just one of these behind an interface and just call the interface whenever you need the time, but what if you legitimately want a hodgepodge of both your server's time and the universal time in your application. Well, if you hand back DateTime.Now you may then use .ToUniversalTime() to cast it to universal time outside of the interface, but as this reveals, this hack is done assuming that a time is local and then calculating what it would take to offset the local time to universal time before finally warping what is in the DateTime type based on the calculation. If you ever change out what is behind the interface away from DateTime.Now you're in trouble and if you can't make such a change then you haven’t really isolated an external dependency. The solution is going to be to put DateTimeOffset.Now or DateTimeOffset.UtcNow behind the interface thus returning a DateTimeOffset which you need to cast into a DateTime outside of the interface like so:

DateTimeOffset dateTimeOffset = DateTime.UtcNow;
DateTime dateTime = dateTimeOffset.DateTime;

 
 

Before undertaking such a casting you may do a .ToUniversalTime() off of the DateTimeOffset type and expect results not to vary based upon what the interface doles out for the time.

No comments:

Post a Comment