Creating a DateTime in a specific Time Zone in c#

后端 未结 7 1729
自闭症患者
自闭症患者 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 10:58

    The other answers here are useful but they don't cover how to access Pacific specifically - here you go:

    public static DateTime GmtToPacific(DateTime dateTime)
    {
        return TimeZoneInfo.ConvertTimeFromUtc(dateTime,
            TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));
    }
    

    Oddly enough, although "Pacific Standard Time" normally means something different from "Pacific Daylight Time," in this case it refers to Pacific time in general. In fact, if you use FindSystemTimeZoneById to fetch it, one of the properties available is a bool telling you whether that timezone is currently in daylight savings or not.

    You can see more generalized examples of this in a library I ended up throwing together to deal with DateTimes I need in different TimeZones based on where the user is asking from, etc:

    https://github.com/b9chris/TimeZoneInfoLib.Net

    This won't work outside of Windows (for example Mono on Linux) since the list of times comes from the Windows Registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\

    Underneath that you'll find keys (folder icons in Registry Editor); the names of those keys are what you pass to FindSystemTimeZoneById. On Linux you have to use a separate Linux-standard set of timezone definitions, which I've not adequately explored.

提交回复
热议问题