What Time Is It?

29 February 2012 by Stuart Cam

Time is an interesting concept, perhaps even something we take for granted in our universe! Leap years and daylight savings are just two human-imposed time counting quirks that crop up now and then, and can cause all manner of problems with poorly designed systems.

var oldDate = Convert.ToDateTime(DateTime.Now.Day + "/" + DateTime.Now.Month + "/" + (DateTime.Now.Year - this.TimeAtAddress));

The above code will work absolutely fine, until you hit a leap year, like today. The code is then at risk of failing if TimeAtAddress is not divisible by 4, in the process littering your error logs with random failures and likely impacting your business in some negative way.

When dealing with DateTime objects ALWAYS use the built in modifiers, for example .AddYears() and .AddMonths(). It'll save you the heartache of having to fix simple date bugs.

When developing applications it's always worth considering how you handle your representation of time, and often it's worth introducing a time abstraction simply to buy you flexibility around testing.

I've used classes such as the one below to push the calculation of the current date into an abstraction that allows you to override the calculation should you need to.

public static class DateHelper
    public static Func DateTimeGenerator = () => DateTime.Now;

    public static DateTime Now()
        return DateTimeGenerator();


var now = DateHelper.Now(); // will get the current date

DateHelper.DateTimeGenerator = () => DateTime.Now.AddDays(5);
var nowPlus5Days = DateHelper.Now(); // will be the current date time plus 5 days

This becomes particularly useful in scenarios where you'd like to setup some test data for something that happened in the past, in order to validate something that occurs in the future. With some clever use of IDisposable it's possible to construct setups for tests such as:

public void A_test(){

	// we are at current time.
	using (var _ = DateTime.ShiftDays(-30))
		// we are now 30 days ago.
	// we are at current time.

If you are feeling really fancy you could start nesting the using() statements and skip back and forth through time as you see fit.


Categories: C Sharp


Leave A Comment

  • Comment
  • Preview

© Codebrain 2022. All Rights Reserved. Registered in England: 07744920. VAT: GB 119 4078 13