How to build a time machine

If you had a time machine, I’m sure you would use it. I have good news for you: I can show you how to build one! At least a software based one…

I think the greatest thing about software development is that we create things in our heads. We live in an imaginary world. Building constantly castles and cathedrals out of nothing but thoughts. No wonder we can build a machine to travel time in this world!

It is actually very simple but highly useful. I show you first a simple implementation in C#/.NET:

namespace TodescoTechnologies.Util 

    /// An artificial Clock. You can change the time  
    /// for test cases without changing the systemtime. 
    public static class DateTimeProvider 
        private static DateTime? mockDateTime = null;   

        /// Set by test cases. This time is returned  
        /// instead of "Now" if set. 
        public static DateTime? MockDateTime 
            set { DateTimeProvider.mockDateTime = value; } 

        /// If no MockDateTime is defined this will  
        /// return the system time. 
        /// If MockDateTime is definied it will return  
        /// MockDateTime.
        public static DateTime Now 
                if (mockDateTime == null) 
                    return DateTime.Now; 
                    return mockDateTime.Value; 

All you have to do is use the DateTimeProvider.Now method instead of DateTime.Now. This will allow you to construct unit tests that happen in the future, mimic the change of a year or daylight savings time changes. All of this without having to change the system time on your development machine or server! You can even fast forward through time and see the state of your system if you have a transaction every ten minutes during a year…

Of course there is room for improvement in my time machine:

  • You can make sure nobody is setting a MockDateTime in your released software. All you have to do is put the MockDateTime property in a conditional directive (You know: #if DEBUG, #endif) and you will have a guarantee that in your released software the time is always accurate. Of course you can use a TEST solution configuration if you have defined such a thing.
  • Instead of having a static MockDateTime this could be an offset.
  • You could implement the accelerated Time with the help of a Timer.

However I found a static set time for unit tests and demos sufficient. It has been very useful in many of the projects I worked on over the years and all it takes is this short piece of code!

4 thoughts on “How to build a time machine

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>