Feb 18, 2021

C#: Get current time in any timezone

 Add reference to nuget package "NodaTime"


        public static DateTime ConvertToTimeZoneFromUtc(DateTime utcDateTime, string timezone= "Europe/Istanbul")
        {
            var easternTimeZone = DateTimeZoneProviders.Tzdb[timezone];
            return Instant.FromDateTimeUtc(utcDateTime)
                          .InZone(easternTimeZone)
                          .ToDateTimeUnspecified();
        }

 

usage:

 var date = ConvertToTimeZoneFromUtc(DateTime.Now.ToUniversalTime());

No comments:

Post a Comment

Be the first to comment on this post.