Tag Archives: datetime

Avoiding DateTime.Now

Codebetter.com has an interesting blog entry about avoiding DateTime.Now. It’s not completely clear from the article, but the problem it is referring to is that of building test cases for code that uses DateTime.Now. If you have code that directly uses “Now” is its calculations, it can be hard for the test code to anticipate the correct output of the these computations. This is mainly because you have to build all of your test cases off of the current time in which case the results of the test cases might not be reproducible — they might pass/fail differently depending on when they were run. Another problem is that the test code can’t know the exact time the tested code will use in it’s computations because it cannot get the exact same “Now” value as the tested code. This is less of a problem if the computations are only accurate to a second, minute, hour, etc.

The solution proposed by the post is to create interfaces for various date time functions, and then write implementation to the interfaces that map to the underlying DateTime.Now value. This way, when you are testing, you can always mock the wrapper classes and return a constant date/time to test various logical scenarios.

.NET Default Numeric String Formatting not Reflexive?

Does the following look like it should throw an exception?

Double.Parse(Double.MaxValue.ToString())

I didn’t think so either, but it turns out I was wrong. Double.MaxValue.ToString() yields 1.79769313486232E+308 when the actual maximum value of a Double is 1.7976931348623157E+308. Ok, we’ll shave off a few digits of precision with the default formatting and round up. Sure…Turns out you need to use the “roundtrip” option…sigh. Thanks to this reference.

Double.Parse(Double.MaxValue.ToString("R"))