Convert To Time Zone With Offset - CSharp System

CSharp examples for System:DateTimeOffset

Description

Convert To Time Zone With Offset

Demo Code


using System;/*from  www  .ja  v  a2s .com*/
using NodaTime;

public class Main{
        public static DateTimeOffset ConvertToTimeZoneWithOffset(this DateTime dateTime, DateTimeZone timeZone)
        {
            timeZone.ThrowIfNull("timeZone");

            if (dateTime.Kind != DateTimeKind.Utc)
                throw new InvalidOperationException("Source DateTime must be in UTC");

            if (timeZone == DateTimeZone.Utc)
                return dateTime;

            return Instant.FromDateTimeUtc(dateTime).InZone(timeZone).ToDateTimeOffset();
        }
        public static DateTimeOffset ConvertToTimeZoneWithOffset(this DateTime dateTime, string timeZoneId)
        {
            timeZoneId.ThrowIfNull("timeZoneId");

            var timeZone = DateTimeZoneProviders.Tzdb[timeZoneId];
            return dateTime.ConvertToTimeZoneWithOffset(timeZone);
        }
}

Related Tutorials