How to get UTC time based on a DateTime and a TimeZone Offset?

I have a datetime object, and I know the UTC offset (double). How can I get UTC time from these two pieces of information?

All of the examples I've seen require a timezone. Well, I don't know what timezone is, and it shouldn't really matter. If i have an offset of -7, it could either be PDT, or it could be MST - it's really irrelevant as either would produce the same UTC. It seems really stupid that I have to convert the offset that I have to a timezone just so the "ToUniversalTime" can pull the offset back out.

Honestly, I'm about to resort to just using something like this:

DateTime dateTime = new DateTime(2014, 8, 6, 12, 0, 0);
Double timeZone = -7.0;
string utc = String.Format("{0}-{1}-{2}T{3}:{4}:{5}{6}:{7}", startDate.Year, startDate.Month, startDate.Day, startDate.Hour, startDate.Minute, startDate.Second, (int) Math.Floor(timeZone), (timeZone % 1) * 60);

can someone please tell me why this is a bad idea?

(someone will probably close this as a duplicate, but I looked at a dozen other questions and none of them were quite the same - they all used the TimeZoneInfo object).

Jon Skeet
people
quotationmark

Just use DateTimeOffset:

TimeSpan utcOffset = TimeSpan.FromHours(timeZone);
DateTimeOffset result = new DateTimeOffset(dateTime, utcOffset);
DateTime utc = result.UtcDateTime;

or

string utc = result.ToString("yyyy-MM-dd'T'HH:mm:ssK", CultureInfo.InvariantCulture);

It's not clear why you want it as a string in the end though...

(You might also want to consider using my Noda Time project, particularly as you're likely to see time zone IDs which are TZDB time zones...)

people

See more on this question at Stackoverflow