Fundamentally, you need DateTimeZone.GetUtcOffset
, which accepts an Instant
.
If the DateTime
value always has a Kind
of Utc
, you can use Instant.FromDateTimeUtc
. If it might have a different Kind
, you'll need to work out more detailed requirements.
Next you need an IDateTimeZoneProvider
to map the time zone ID into a DateTimeZone
. That might be DateTimeZoneProviders.Tzdb
, or it might be one you've injected somewhere for testability.
Once you've got the Instant
and the DateTimeZone
, you can call GetUtcOffset
to get an Offset
. You can convert that back to a TimeSpan
, but I'd actually encourage you to avoid using DateTime
and TimeSpan
as far as possible in your app - if you can use the Noda Time types everywhere within your codebase and only convert between those and the BCL types at boundaries (e.g. database access) you'll find you need to do a lot less of this work.
But if you really need a TimeSpan
, the method would look like this:
TimeSpan GetTimeZoneOffset(string timeZoneId, DateTime dateTimeUtc)
{
Instant instant = Instant.FromDateTimeUtc(dateTimeUtc);
DateTimeZone zone = DateTimeZoneProviders.Tzdb[timeZoneId];
Offset offset = zone.GetUtcOffset(instant);
return offset.ToTimeSpan();
}
Note that the IDateTimeZoneProvider[string]
indexer will throw an exception if the time zone isn't found in that provider. If you want to handle this a different way, use IDateTimeZoneProvider.GetZoneOrNull()
and check whether the result is null or not.
DateTime
with aKind
of UTC? Your example answer assumes so, but it's really important. (What if it's aKind
of Unspecified, and that value is skipped or ambiguous?Instant
andOffset
rather thanDateTime
andTimeSpan
) for as much of the code as possible. Only convert to BCL types at the boundaries of your code, if you need to for compatibility.Kind
ofDateTime
you need to be able to handle. Will it only ever be UTC?