views:

66

answers:

2

I have this line of code:

double seconds = new DateTime(2006,7,6,12,1,0,DateTimeKind.Local).Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Local).TotalSeconds;

This was not the right number I wanted, so I tried the following:

double seconds = new DateTime(2006,7,6,12,1,0,DateTimeKind.Local).Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc).TotalSeconds;

(The difference is that in one case, I use local time for the epoch, and in the other, I use UTC). Interestingly though, they're both giving me the same value, and I don't know why this is. I live at -600 GMT, so DateTimeKind.Local should actually affect things.

Thanks in advance!

+2  A: 

In the DateTimeKind page on MSDN (http://msdn.microsoft.com/en-us/library/shx7s921.aspx), it states:

The members of the DateTimeKind enumeration are used in conversion operations between local time and Coordinated Universal Time (UTC), but not in comparison or arithmetic operations. For more information about time conversions, see Converting Times Between Time Zones.

The advice there says to use TimeZoneInfo.ConvertTimeToUtc

So, based on that, the code should probably be modified to:

double seconds = new DateTime(2006,7,6,12,1,0,DateTimeKind.Local).Subtract(TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970,1,1,0,0,0,DateTimeKind.Local)).TotalSeconds
mkedobbs
for the record, it actually ended up being this: double seconds = TimeZoneInfo.ConvertTimeToUtc(new DateTime(2006,7,6,12,1,0,DateTimeKind.Local)).Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Local).TotalSeconds
codersarepeople
+1  A: 

Try this:

namespace ConsoleApplication1
{
    using System;

    class Program
    {
        static void Main( string[] args )
        {
            var laterDate = new DateTime( 2006, 7, 6, 12, 1, 0 );
            var earlyDate = new DateTime( 1970, 1, 1, 0, 0, 0 );
            var diff = laterDate.ToUniversalTime().Subtract( earlyDate.ToUniversalTime() );
            var seconds = diff.TotalSeconds;
        }
    }
}
Adel Hazzah