My service requests data from an external service that needs an argument for a particular date (doesn't need time information).
Until now, I've been using DateTime.Today (e.g. 10/24/2014 12:00:00).
I've moved to using NodaTime for improved testability but not sure of the best way to replicate this functionality:
public class SomeClass(IClock clock)
{
_clock = clock; //Injected at runtime, provides mockable interface
var localNow = _clock.Now.InZone(_serverTimeZone);
var today = localNow.ToDateTimeUnspecified().Date; //This close enough? Seems kinda long
}
To represent a date, you should use LocalDate
rather than DateTime
, ideally. So you want:
var localNow = clock.Now.InZone(serverZone);
var today = localNow.Date;
If you must use DateTime
, then your current code is fine.
In Noda Time 2.0, this will be simpler due to a ZonedClock
which is basically a composite of a clock and a time zone, allowing you to write:
// Or whatever...
private readonly ZonedClock zonedClock = clock.InZone(zone);
// Then later
LocalDate date = zonedClock.GetCurrentDate();
Noda Time 2.0 isn't ready for release yet, but I wanted to give you an idea of what's coming.
See more on this question at Stackoverflow