Search code examples
c#datetimetimezone

C# setting or update only the timezone value, not converting


I am constructing a new C# DateTime from int values for year, month, day, hours, minutes & seconds. The values are already adjusted for the destination timezone. (I cannot change that. I am given those values).

Now, when I construct the new DateTime (year, month, ...) it's timezone is the timezone of my PC (system), which is different from the destination timezone.

Without converting my output DateTime (the actual time is correct and it's already adjusted for the destination timezone), how do I only update/set is timezone or DateTimeOffset? So, far the only way I was able to make it work was by setting my system timezone to the destination timezone. I don't want to keep doing that.

Tried different DateTime libraries. But all they do is CONVERT. I do not need to convert. Only set the timezone.


Solution

  • The DateTimeOffset(int,int,int,int,int,int,TimeSpan) Constructor might be what you're looking for. It takes the Y,M,D,H,M,S integer parameters as you are expecting, but it also takes a TimeSpan, which is the UTC offset for the given time zone.

    If you set it to the right UTC offset (for example, new TimeSpan(-5, 0, 0) for UTC-5), you can get the local time AND the UTC time (offsetDate.UtcDateTime)