ConvertTimeToUtc exception

Hello, I have an exception when converting local time to UTC. I launched the application on Windows with Russian Standard Time installed.

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

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

            // now let 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 - cannot complete coversion because the Kind datetime property is incorrect. For example, if Kind is local, the time zone should be TimeZoneInfo.Local.

Sorry, this is not a copy - the original message is not written in English.

+3
source share
2 answers

TimeZoneInfo.Equals Id: , (TimeZoneInfo.HasSameRules) - Reflector.

, , TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time") .

.

+1

msdn :

ArgumentException
dateTime.Kind - DateTimeKind.Utc, sourceTimeZone TimeZoneInfo.Utc.
--
dateTime.Kind - DateTimeKind.Local sourceTimeZone TimeZoneInfo.Local.

, , . DateTime.Now DateTimeKind.Local.
DateTime.SpecifyKind() :

dt1 = DateTime.SpecifyKind( dt, DateTimeKind.Unspecified );
TimeZoneInfo.ConvertTimeToUtc( dt1, tz );
+1

Source: https://habr.com/ru/post/1755286/


All Articles