Creating a DateTime in a specific Time Zone in c#

后端 未结 7 1800
自闭症患者
自闭症患者 2020-11-22 10:24

I\'m trying to create a unit test to test the case for when the timezone changes on a machine because it has been incorrectly set and then corrected.

In the test I n

7条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 11:09

    Jon's answer talks about TimeZone, but I'd suggest using TimeZoneInfo instead.

    Personally I like keeping things in UTC where possible (at least for the past; storing UTC for the future has potential issues), so I'd suggest a structure like this:

    public struct DateTimeWithZone
    {
        private readonly DateTime utcDateTime;
        private readonly TimeZoneInfo timeZone;
    
        public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
        {
            var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
            utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone); 
            this.timeZone = timeZone;
        }
    
        public DateTime UniversalTime { get { return utcDateTime; } }
    
        public TimeZoneInfo TimeZone { get { return timeZone; } }
    
        public DateTime LocalTime
        { 
            get 
            { 
                return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); 
            }
        }        
    }
    

    You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.

提交回复
热议问题