Martijn
Martijn

Reputation: 12102

Build DateTimeOffset from unspecified DateTime and Timezone name

I have a DateTime dt, which has a date and time of some local instant and a String tz specifying the timezone name for that datetime. How do I get a DateTimeOffset struct fully representing the DateTime?

I can get the timezone info with TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(csf.TimezoneName);

but I'm now unsure how to get the DateTimeOffset I want from these two elements

Upvotes: 1

Views: 491

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241890

You can convert a local time in a particular zone to a DateTimeOffset like this:

DateTime dt = new DateTime(2013, 1, 1, 0, 0, 0);
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTimeOffset dto = new DateTimeOffset(dt, tzi.GetUtcOffset(dt));

Just be aware that if the input time is ambiguous or invalid due to daylight saving time, it will use the zone's standard offset.

Upvotes: 3

Related Questions