tags:

views:

38

answers:

2

Hello I have an exception when converting local time to UTC. I run my application on Windows where "Russian Standard Time" is set.

public Convert()
{
            DateTime dt = DateTime.Now;
            DateTime dt1 = DateTime.Now;

           // this converstion works
            TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Local);

            // now let's get local timezone by id
            TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time");

            if (TimeZoneInfo.Local.Id == tz.Id)
            {
                // this is just to make sure we have the same timezones
            }

// this conversion does not work
// throws exception System.ArgumentException
TimeZoneInfo.ConvertTimeToUtc(dt1, tz);

}

UPDATE

Exception text is saying - cannot complete coversion because Kind property of datetime is wrong. For example if Kind is Local the timezone must have value of TimeZoneInfo.Local.

Sorry this is not a copypaste - original message is not in english.

+1  A: 

msdn says:

ArgumentException
dateTime.Kind is DateTimeKind.Utc and sourceTimeZone does not equal TimeZoneInfo.Utc.
-or-
dateTime.Kind is DateTimeKind.Local and sourceTimeZone does not equal TimeZoneInfo.Local.

and that seems to be the problem. DateTime.Now returns a DateTimeKind.Local.
But using DateTime.SpecifyKind() works for me:

dt1 = DateTime.SpecifyKind( dt, DateTimeKind.Unspecified );
TimeZoneInfo.ConvertTimeToUtc( dt1, tz );
tanascius
Yes it works for me too. When DateTime.Kind is set to Unspecified it is ok.
Captain Comic
But i wonder why the exception is thrown? That could only meanthere is TimeZoneInfo reference check against TimeZoneInfo.Local
Captain Comic
@Captain: yes, it seems that the method compares *TimeZoneInfo* and *DateTimeKind*
tanascius
+1  A: 

The TimeZoneInfo.Equals method does not only compare on the Id: it also tests that the two timezones have the same adjustment rules (TimeZoneInfo.HasSameRules) - you can see this using Reflector.

I suspect that the Local timezone is in fact using daylight savings time, whereas TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time") is returning a timezone without daylight savings time.

You should be able to check this easily using the debugger.

Joe