Convert UTC DateTime to another Time Zone

前端 未结 5 1756
渐次进展
渐次进展 2020-12-02 23:02

I have a UTC DateTime value coming from a database record. I also have a user-specified time zone (an instance of TimeZoneInfo). How do I convert that UTC DateTime to the us

5条回答
  •  眼角桃花
    2020-12-02 23:19

    The Antartica answer only works for the timezones matching UTC. I'm quite traumatized with this DateTimeOffset function and after hours of trial and error, I've managed to produce a practical conversion extension function that works with all timezones.

    static public class DateTimeFunctions
    {
        static public DateTimeOffset ConvertUtcTimeToTimeZone(this DateTime dateTime, string toTimeZoneDesc)
        {
            if (dateTime.Kind != DateTimeKind.Utc) throw new Exception("dateTime needs to have Kind property set to Utc");
            var toUtcOffset = TimeZoneInfo.FindSystemTimeZoneById(toTimeZoneDesc).GetUtcOffset(dateTime);
            var convertedTime = DateTime.SpecifyKind(dateTime.Add(toUtcOffset), DateTimeKind.Unspecified);
            return new DateTimeOffset(convertedTime, toUtcOffset);
        }
    }
    

    Example:

    var currentTimeInPacificTime = DateTime.UtcNow.ConvertUtcTimeToTimeZone("Pacific Standard Time");
    

提交回复
热议问题