开发者

C# DateTime time zone subtract issues

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.Loc开发者_运维百科al should actually affect things.

Thanks in advance!


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


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;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜