2

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).

matthew_360
  • 5,901
  • 9
  • 32
  • 40
  • 2
    Why not `DateTime.AddHours` or `+ TimeSpan `? Side note: there are "30 minutes" timezones, so be careful with your hour rounding. – Alexei Levenkov Aug 06 '14 at 19:52
  • because I need to convert it to UTC time and when doing so it uses my local timezone, and not the one I provide. I suppose I could do some substraction and subtract or add the difference between the local timezone and the desired timezone, and then convert it to UTC... but that still seems unnecessary. – matthew_360 Aug 06 '14 at 19:53
  • http://stackoverflow.com/questions/3361861/convert-utc-time-and-offset-to-datetime – Marcel N. Aug 06 '14 at 19:53
  • 1
    This feels like an XY problem. Please give more context about exactly what you're trying to accomplish. Do you *actually* need it as a string, or are you looking for something else? – Jon Skeet Aug 06 '14 at 19:54
  • I'm creating a Google Calendar event through their API – matthew_360 Aug 06 '14 at 19:55
  • Marcel: that's going the opposite direction. – matthew_360 Aug 06 '14 at 19:56
  • 1
    Just mind the time light saving issue, especially if you hard code your offset! – FeliceM Aug 06 '14 at 20:00

1 Answers1

6

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...)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194