Exception on ConvertTimeToUtc
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;
DateTim开发者_高级运维e 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.
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.
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 );
精彩评论