none
DateTime.Subtract doesn't account for the long and short hours RRS feed

  • Question

  • Hi,

    I've been trying to figure out why the following test case fails, it seems that the subtract inside the DateTime class fails to account for the long and short hours in its calculation...

        [TestClass]
        public class TimeZoneTests
        {
            [TestMethod]
            public void ShouldGetCorrectNumberOfHoursBetweenTwoDates()
            {
                DateTime date1 = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(new DateTime(2013, 10, 01, 6, 0, 0, DateTimeKind.Utc), "GMT Standard Time");
                DateTime date2 = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(new DateTime(2013, 11, 01, 6, 0, 0, DateTimeKind.Utc), "GMT Standard Time");
    
                var answer = date2.Subtract(date1);
                Assert.AreEqual(745, answer.TotalHours);
            }
        }
    

    Does anyone know what I'm doing wrong?

    Thursday, October 10, 2013 12:08 PM

Answers

  • Hi. You are going over a clock change here (BST to GMT on 27/10/2013) which I think could be causing a problem as .net is taking account of it. If you look at the dates date2 will have the correct time of 06:00 but Date1 is still in BST so has a time of 07:00. Then with those two date times the total hours is 743.
    • Edited by JayChase Thursday, October 10, 2013 12:32 PM
    • Marked as answer by Damon Bu - MSFT Thursday, October 17, 2013 2:56 AM
    Thursday, October 10, 2013 12:31 PM