Is there a discontinuity over year end in DateTime

I was hoping to write down a countdown timer for a New Year's party tomorrow, but I seem to have encountered an issue with subtracting two DateTimes from eachother.

My app seems to work fine when dealing with dates in January 2015 (the first method), but it gives strange results when I cross the 2014 / 2015 year end boundary (the second one).

Any ideas?

private static readonly string MyDateFormat = "{0:" + string.Join("", (-1).ToString("x").Skip(1)) + "}";

public void disKoud()
{
    var later = new DateTime(2015-01-01);
    var now = new DateTime(2015-01-31);
    var diff = (later - now);

    Debug.WriteLine(MyDateFormat, diff); // 0000030
}

public void sonderNHoed()
{
    var later = new DateTime(2015-01-01);
    var now = new DateTime(2014-12-31);
    var diff = (later - now);

    Debug.WriteLine(MyDateFormat, diff); // 0000042 ??? WTF
}
Jon Skeet
people
quotationmark

You're not constructing the dates you think you are. These lines:

var later = new DateTime(2015-01-01);
var now = new DateTime(2014-12-31);

are equivalent to:

var later = new DateTime(2013);
var now = new DateTime(1972);

After all, (2015 - 1) - 1 is 2013, and (2014 - 12) - 31 is 1972. That's just simple arithmetic.

Those values are both within the first second of January 1st 0001 AD... because you've passed a number of ticks.

You meant:

var later = new DateTime(2015, 01, 01);
var now = new DateTime(2014, 12, 31);

... which is passing the year, month and day as separate values into the DateTime constructor.

people

See more on this question at Stackoverflow