The Power of Using a Domain Model for Time in .NET

while (true) {
if (DateTime.Now.Hour == 12 && DateTime.Now.Minute == 0)
{
Console.WriteLine("Time for lunch!");
SetCalendar("Back in 30 minutes.");
return;
}
Thread.Sleep(1000);
}
private DateTime GetLocalTime(DateTime datetime, int offset)
{
if (datetime.Kind != DateTimeKind.Utc)
{
throw new Exception("Needs to be UTC");
}
var local = new DateTime(datetime.Year, datetime.Month, datetime.Day, datetime.Hour, datetime.Minute, datetime.Second, DateTimeKind.Local);
local = local.Add(TimeSpan.FromHours(offset));
return local;
}
while (true) 
{
var now = GetLocalTime(DateTime.UtcNow, -7);
if (now.Hour == 12 && now.Minute == 0)
{
Console.WriteLine("Time for lunch!");
SetCalendar("Back in 30 minutes.");
return;
}
Thread.Sleep(1000);
}

Enter domain time.

var domainTime = MyDomainTime.FromLocal(TimeZoneHelper.UsPacific); 
if (domainTime.IsLunchtime())
{
Console.WriteLine("Time for lunch!");
SetCalendar("Back in 30 minutes.");
return;
}
Thread.Sleep(1000);
private static Func<DateTime> _funcForDeterminingNow;
public DateTimeOffset Now()
{
var now = _funcForDeterminingNow.Invoke();
return TimeZoneHelper.GetDateTimeOffset(_timeZone, now);
}
_funcForDeterminingNow = () => DateTime.UtcNow;
public static void SetNow(Func<DateTime> nowFunc) 
{
_funcForDeterminingNow = nowFunc;
}
[TestMethod] 
public void MyTest()
{
MyDomainTime.SetNow(() => new DateTime(2015, 11, 4, 8, 45, 12, DateTimeKind.Utc));
var now = MyDomainTime.FromLocal("US/Pacific").Now();
Assert.AreEqual(2015, now.Year);
Assert.AreEqual(11, now.Month);
Assert.AreEqual(4, now.Day);
Assert.AreEqual(0, now.Hour); // should be the local hour, given the UTC-8 for this date
Assert.AreEqual(45, now.Minute);
Assert.AreEqual(12, now.Second);
Assert.AreEqual(new TimeSpan(-8, 0, 0), now.Offset);
}

Beyond “now”

public static int CompanyYearOfIncorporation => 2013;
public static string MonthThatContainsAllTheMadness => "March";
public bool IsExpired(DateTime expirationDate)
{ /* ignore the time component of the input date and compare against midnight local time */ }
public DateTimeOffset StartOfTotalSolarEclipse();

In summary

About iTrellis

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store