Search code examples
c#datetimeutclocaltime

DateTime.ToUniversalTime() not correct


I have a problem with the ToUniversalTime() method.

A little bit of information first: I live and work in germany, so my standard time zone is UTC+1. But now (in summer) my time zone is UTC+2.

I need to convert my local time to UTC for my application. So I tried at first:

OutputTime = InputTime.ToUniversalTime();

but that only subtracted 1 hour instead of two. After a little bit of research I discoverd that InputTime.Kind was Unspecified, so I tried:

InputTime= DateTime.SpecifyKind(InputTime, DateTimeKind.Local);
OutputTime = InputTime.ToUniversalTime();

but still get the same problem.

And my biggest problem is that if I try this

TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now)

it gives me a timespan of two hours.

Any ideas please? Thanks


Solution

  • Not sure if it's the best solution, but this certainly works:

    var InputTime = new DateTime(2016, 10, 12, 12, 22, 0, DateTimeKind.Local);
    var offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
    var OutputTime = DateTime.SpecifyKind(InputTime - offset, DateTimeKind.Utc);