//
        // enumerate all time zones till find a match and with valid key name
        //
        internal static unsafe bool FindMatchToCurrentTimeZone(TimeZoneInformation timeZoneInformation)
        {
            uint index  = 0;
            uint result = 0; // ERROR_SUCCESS
            bool notSupportedDaylightSaving    = CheckDaylightSavingTimeNotSupported(timeZoneInformation);
            TIME_DYNAMIC_ZONE_INFORMATION tdzi = new TIME_DYNAMIC_ZONE_INFORMATION();

            while (result == 0)
            {
                result = Interop.mincore.EnumDynamicTimeZoneInformation(index, out tdzi);
                if (result == 0)
                {
                    string s = new String(tdzi.StandardName);

                    if (!String.IsNullOrEmpty(s) &&
                        EqualStandardDates(timeZoneInformation, ref tdzi) &&
                        (notSupportedDaylightSaving || EqualDaylightDates(timeZoneInformation, ref tdzi)) &&
                        String.Compare(s, timeZoneInformation.StandardName, StringComparison.Ordinal) == 0)
                    {
                        // found a match
                        timeZoneInformation.TimeZoneKeyName = s;
                        return(true);
                    }
                }
                index++;
            }

            return(false);
        }
Пример #2
0
        private TimeZoneInfo(TimeZoneInformation zone, bool dstDisabled)
        {
            if (string.IsNullOrEmpty(zone.StandardName))
            {
                _id = LocalId;  // the ID must contain at least 1 character - initialize m_id to "Local"
            }
            else
            {
                _id = zone.StandardName;
            }
            _baseUtcOffset = new TimeSpan(0, -(zone.Dtzi.Bias), 0);

            if (!dstDisabled)
            {
                // only create the adjustment rule if DST is enabled
                AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(zone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Dtzi.Bias);
                if (rule != null)
                {
                    _adjustmentRules    = new AdjustmentRule[1];
                    _adjustmentRules[0] = rule;
                }
            }

            ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
            _displayName         = zone.StandardName;
            _standardDisplayName = zone.StandardName;
            _daylightDisplayName = zone.DaylightName;
        }
Пример #3
0
        public static DateTime ObtemDataHoraSistema()
        {
            DateTime retorno;

            try
            {
                TimeZoneInformation tmznfo = new TimeZoneInformation();
                GetTimeZoneInformation(out tmznfo);

                SYSTEMTIME datahorasistema = new SYSTEMTIME();
                GetSystemTime(out datahorasistema);

                DateTime datalocal = new DateTime(datahorasistema.wYear, datahorasistema.wMonth, datahorasistema.wDay, datahorasistema.wHour, datahorasistema.wMinute, datahorasistema.wSecond, datahorasistema.wMilliseconds);

                TimeZoneInfo.ClearCachedData();
                TimeZoneInfo nfo = TimeZoneInfo.Local;

                datalocal = datalocal.AddMinutes(-tmznfo.bias);

                if (!nfo.IsDaylightSavingTime(datalocal))
                {
                    retorno = datalocal;
                }
                else
                {
                    retorno = datalocal.AddMinutes(-tmznfo.daylightBias);
                }
            }
            catch
            {
                retorno = DateTime.Now;
            }

            return(retorno);
        }
Пример #4
0
        public void TimzeZoneChangeTest()
        {
            TimeZoneInformation currentTzi = new TimeZoneInformation();

            DateTimeHelper.GetTimeZoneInformation(ref currentTzi);

            try
            {
                TimeZoneInformation expectedTzi = new TimeZoneInformation();
                expectedTzi.Bias         = currentTzi.Bias + 60; // (add an hour)
                expectedTzi.StandardName = "Standard Lunar Time";
                expectedTzi.DaylightName = "Daylight Lunar Time";

                DateTimeHelper.SetTimeZoneInformation(expectedTzi);

                TimeZoneInformation retrievedTzi = new TimeZoneInformation();
                DateTimeHelper.GetTimeZoneInformation(ref retrievedTzi);

                Assert.AreEqual(expectedTzi.Bias, retrievedTzi.Bias);
                Assert.AreEqual(expectedTzi.StandardName, retrievedTzi.StandardName);
                Assert.AreEqual(expectedTzi.DaylightName, retrievedTzi.DaylightName);
            }
            finally
            {
                DateTimeHelper.SetTimeZoneInformation(currentTzi);
            }
        }
Пример #5
0
        /// <summary>
        /// 设置本地时区
        /// </summary>
        /// <param name="timeZoneName_en"></param>
        /// <returns></returns>
        public static bool SetLocalTimeZone(string timeZoneName_en)
        {
            if (PrivilegeAPI.GrantPrivilege(PrivilegeConstants.SE_TIME_ZONE_NAME))
            {
                DynamicTimeZoneInformation dtzi = timeZoneName2DynamicTimeZoneInformation(timeZoneName_en);
                bool success = false;

                // 检测当前系统是否为旧系统
                if (IsOldOsVersion())
                {
                    Console.WriteLine("检测当前系统为: Old OS Version");
                    TimeZoneInformation tzi = DynamicTimeZoneInformation2TimeZoneInformation(dtzi);
                    success = SetTimeZoneInformation(ref tzi);
                }
                else
                {
                    success = SetDynamicTimeZoneInformation(ref dtzi);
                }

                if (success)
                {
                    TimeZoneInfo.ClearCachedData();  // 清除缓存
                }

                if (!PrivilegeAPI.RevokePrivilege(PrivilegeConstants.SE_TIME_ZONE_NAME))
                {
                    Console.WriteLine("撤权失败: 更改时区");
                }

                return(success);
            }

            Console.WriteLine("授权失败: 更改时区");
            return(false);
        }
Пример #6
0
        /// <summary>
        /// Set time zone
        /// </summary>
        /// <param name="tzi"></param>
        /// <returns></returns>
        public static bool SetTimeZone(TimeZoneInformation tzi)
        {
            //ComputerManager.EnableToken("SeTimeZonePrivilege", Process.GetCurrentProcess().Handle);

            // set local system timezone

            return(SetTimeZoneInformation(ref tzi));
        }
 /// <summary>
 /// Sets new time-zone information for the local system.
 /// </summary>
 /// <param name="tzi">Struct containing the time-zone parameters to set.</param>
 public static void SetTimeZone(TimeZoneInformation tzi)
 {
     // set local system timezone
     if (!SetTimeZoneInformation(ref tzi))
     {
         throw new Win32Exception(Marshal.GetLastWin32Error());
     }
 }
Пример #8
0
        /// <summary>
        /// Get all time zone informations
        /// </summary>
        /// <returns></returns>
        private static TimeZoneCollection GetTimeZones()
        {
            lock (_SyncRoot)
            {
                if (_Zones != null)
                {
                    return(_Zones);
                }

                //open key where all time zones are located in the registry

                RegistryKey timeZoneKeys = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones");

                //create a new hashtable which will store the name

                //of the timezone and the associate time zone information struct

                _Zones = new TimeZoneCollection();

                //iterate through each time zone in the registry and add it to the hash table

                foreach (string zonekey in timeZoneKeys.GetSubKeyNames())
                {
                    //get current time zone key

                    RegistryKey individualZone = timeZoneKeys.OpenSubKey(zonekey);

                    //create new TZI struct and populate it with values from key

                    TimeZoneInformation TZI = new TimeZoneInformation();

                    TZI.standardName = individualZone.GetValue("Std").ToString();

                    string displayName = individualZone.GetValue("Display").ToString();

                    TZI.daylightName = individualZone.GetValue("Dlt").ToString();

                    //read binary TZI data, convert to byte array

                    byte[] b = (byte[])individualZone.GetValue("TZI");

                    TZI.bias         = BitConverter.ToInt32(b, 0);
                    TZI.standardBias = BitConverter.ToInt32(b, 4);
                    TZI.daylightBias = BitConverter.ToInt32(b, 8);

                    TZI.standardDate = new SYSTEMTIME(b, 12);
                    TZI.daylightDate = new SYSTEMTIME(b, 28);

                    //Marshal.PtrToStructure(

                    //add the name and TZI struct to hash table

                    _Zones.Add(displayName, TZI);
                }

                return(_Zones);
            }
        }
        public DateTime GetLocalDateTime(string microSiteId)
        {
            var citydatetime = DateTime.Now;

            if (microSiteId == "london" || microSiteId == "international")
            {
                return(DateTime.Now);
            }

            const string timeZonesCacheKey = "TimeZones";

            var timeZoneList = _cacheProvider.GetFromCache <Dictionary <string, TimeZoneInformation> >(timeZonesCacheKey);

            if (timeZoneList == null)
            {
                //read and populate time zones from the registry
                var mZones = TimeZoneInformation.EnumZones();
                Array.Sort(mZones, new TimeZoneComparer());

                timeZoneList = new Dictionary <string, TimeZoneInformation>();

                foreach (var tzone in mZones)
                {
                    if (!timeZoneList.ContainsKey(tzone.Name))
                    {
                        timeZoneList.Add(tzone.Name, tzone);
                    }
                }

                //cache this for 5 mins
                if (timeZoneList.Count > 0)
                {
                    _cacheProvider.AddToCache(timeZonesCacheKey, timeZoneList, DateTime.Now.AddDays(1));
                }
            }

            var tzsn = GetCityTimeZoneStandardName(microSiteId);

            if (!timeZoneList.ContainsKey(tzsn))
            {
                return(citydatetime);
            }

            var destinationTimeZoneInfo = timeZoneList[tzsn];
            var local = DateTime.Now;
            var utc   = local.ToUniversalTime();

            if (destinationTimeZoneInfo == null)
            {
                return(citydatetime);
            }

            var destinationTime = destinationTimeZoneInfo.FromUniversalTime(utc);

            citydatetime = destinationTime;

            return(citydatetime);
        }
Пример #10
0
        //
        // TryGetTimeZone -
        //
        // Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
        //
        // This function may return null.
        //
        // assumes cachedData lock is taken
        //
        private static TimeZoneInfoResult TryGetTimeZone(ref TimeZoneInformation timeZoneInformation, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData)
        {
            TimeZoneInfoResult result = TimeZoneInfoResult.Success;

            e = null;
            TimeZoneInfo match = null;

            // check the cache
            if (cachedData._systemTimeZones != null)
            {
                if (cachedData._systemTimeZones.TryGetValue(timeZoneInformation.TimeZoneKeyName, out match))
                {
                    if (dstDisabled && match._supportsDaylightSavingTime)
                    {
                        // we found a cache hit but we want a time zone without DST and this one has DST data
                        value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
                    }
                    else
                    {
                        value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
                                                 match._daylightDisplayName, match._adjustmentRules, false);
                    }
                    return(result);
                }
            }

            // fall back to reading from the local machine
            // when the cache is not fully populated
            result = TryGetFullTimeZoneInformation(timeZoneInformation, out match, out e, timeZoneInformation.Dtzi.Bias);

            if (result == TimeZoneInfoResult.Success)
            {
                if (cachedData._systemTimeZones == null)
                {
                    cachedData._systemTimeZones = new Dictionary <string, TimeZoneInfo>();
                }

                cachedData._systemTimeZones.Add(timeZoneInformation.TimeZoneKeyName, match);

                if (dstDisabled && match._supportsDaylightSavingTime)
                {
                    // we found a cache hit but we want a time zone without DST and this one has DST data
                    value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
                }
                else
                {
                    value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
                                             match._daylightDisplayName, match._adjustmentRules, false);
                }
            }
            else
            {
                value = null;
            }

            return(result);
        }
Пример #11
0
        /// <summary>
        /// set time zone by display name
        /// </summary>
        /// <param name="displayName">part of display name</param>
        /// <param name="wholeDisplayName">whole display name</param>
        /// <returns></returns>
        public static bool SetTimeZone(string displayName, out string wholeDisplayName)
        {
            //ComputerManager.EnableToken("SeTimeZonePrivilege", Process.GetCurrentProcess().Handle);

            // set local system timezone
            TimeZoneInformation tzi = GetTimeZone(displayName, out wholeDisplayName);

            return(SetTimeZoneInformation(ref tzi));
        }
        private static void SaveTimeZoneInformationToFile(string p)
        {
            TimeZoneInformation timeZoneInformation = GetTimeZone();

            byte[] byteArray = StructureToByteArray(timeZoneInformation);
            using (FileStream f = File.Create(p))
            {
                f.Write(byteArray, 0, byteArray.Length);
            }
        }
Пример #13
0
        public DateTime ToUTC(DateTime dt)
        {
            if ((IsLoggedIn) && (SessionTimeZone > 0))
            {
                TimeZoneInformation tz = TimeZoneInformation.FromIndex(SessionTimeZone);
                return(tz.ToUniversalTime(dt));
            }

            return(dt.Add(-BrowserUtcOffset));
        }
 private static bool CheckDaylightSavingTimeNotSupported(TimeZoneInformation timeZone)
 {
     return(timeZone.Dtzi.DaylightDate.wYear == timeZone.Dtzi.StandardDate.wYear &&
            timeZone.Dtzi.DaylightDate.wMonth == timeZone.Dtzi.StandardDate.wMonth &&
            timeZone.Dtzi.DaylightDate.wDayOfWeek == timeZone.Dtzi.StandardDate.wDayOfWeek &&
            timeZone.Dtzi.DaylightDate.wDay == timeZone.Dtzi.StandardDate.wDay &&
            timeZone.Dtzi.DaylightDate.wHour == timeZone.Dtzi.StandardDate.wHour &&
            timeZone.Dtzi.DaylightDate.wMinute == timeZone.Dtzi.StandardDate.wMinute &&
            timeZone.Dtzi.DaylightDate.wSecond == timeZone.Dtzi.StandardDate.wSecond &&
            timeZone.Dtzi.DaylightDate.wMilliseconds == timeZone.Dtzi.StandardDate.wMilliseconds);
 }
Пример #15
0
        //
        // CreateAdjustmentRuleFromTimeZoneInformation-
        //
        // Converts TimeZoneInformation to an AdjustmentRule
        //
        private static AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(TimeZoneInformation timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset)
        {
            bool supportsDst = (timeZoneInformation.Dtzi.StandardDate.wMonth != 0);

            if (!supportsDst)
            {
                if (timeZoneInformation.Dtzi.Bias == defaultBaseUtcOffset)
                {
                    // this rule will not contain any information to be used to adjust dates. just ignore it
                    return(null);
                }

                return(AdjustmentRule.CreateAdjustmentRule(
                           startDate,
                           endDate,
                           TimeSpan.Zero, // no daylight saving transition
                           TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1),
                           TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1),
                           new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Dtzi.Bias, 0), // Bias delta is all what we need from this rule
                           noDaylightTransitions: false));
            }

            //
            // Create an AdjustmentRule with TransitionTime objects
            //
            TransitionTime daylightTransitionStart;

            if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, true /* start date */))
            {
                return(null);
            }

            TransitionTime daylightTransitionEnd;

            if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, false /* end date */))
            {
                return(null);
            }

            if (daylightTransitionStart.Equals(daylightTransitionEnd))
            {
                // this happens when the time zone does support DST but the OS has DST disabled
                return(null);
            }

            return(AdjustmentRule.CreateAdjustmentRule(
                       startDate,
                       endDate,
                       new TimeSpan(0, -timeZoneInformation.Dtzi.DaylightBias, 0),
                       (TransitionTime)daylightTransitionStart,
                       (TransitionTime)daylightTransitionEnd,
                       new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Dtzi.Bias, 0),
                       noDaylightTransitions: false));
        }
Пример #16
0
 protected void Page_Init(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         TimeZoneInformation[] zones = TimeZoneInformation.EnumZones();
         selectTimezoneControl.Items.Add(new ListItem("Web Browser TimeZone", "-1"));
         foreach (TimeZoneInformation tz in zones)
         {
             selectTimezoneControl.Items.Add(new ListItem(tz.DisplayName, tz.Index.ToString()));
         }
     }
 }
Пример #17
0
        public string AdjustToRFC822(DateTime dt)
        {
            if ((IsLoggedIn) && (SessionTimeZone > 0))
            {
                TimeZoneInformation tz = TimeZoneInformation.FromIndex(SessionTimeZone);
                return(tz.FromUniversalTime(dt).ToString("ddd, dd MMM yyyy HH:mm:ss") +
                       " " + tz.CurrentUtcBias.TotalHours.ToString("00") + tz.CurrentUtcBias.Minutes.ToString("00"));
            }

            return(dt.Add(BrowserUtcOffset).ToString("ddd, dd MMM yyyy HH:mm:ss") +
                   " " + BrowserUtcOffset.TotalHours.ToString("00") + BrowserUtcOffset.Minutes.ToString("00"));
        }
 private static bool EqualDaylightDates(TimeZoneInformation timeZone, ref TIME_DYNAMIC_ZONE_INFORMATION tdzi)
 {
     return(timeZone.Dtzi.DaylightBias == tdzi.DaylightBias &&
            timeZone.Dtzi.DaylightDate.wYear == tdzi.DaylightDate.wYear &&
            timeZone.Dtzi.DaylightDate.wMonth == tdzi.DaylightDate.wMonth &&
            timeZone.Dtzi.DaylightDate.wDayOfWeek == tdzi.DaylightDate.wDayOfWeek &&
            timeZone.Dtzi.DaylightDate.wDay == tdzi.DaylightDate.wDay &&
            timeZone.Dtzi.DaylightDate.wHour == tdzi.DaylightDate.wHour &&
            timeZone.Dtzi.DaylightDate.wMinute == tdzi.DaylightDate.wMinute &&
            timeZone.Dtzi.DaylightDate.wSecond == tdzi.DaylightDate.wSecond &&
            timeZone.Dtzi.DaylightDate.wMilliseconds == tdzi.DaylightDate.wMilliseconds);
 }
Пример #19
0
 public void TestTryParseTimezoneOffsetToTimeSpan()
 {
     TimeZoneInformation[] tzs = TimeZoneInformation.EnumZones();
     foreach (TimeZoneInformation ti in tzs)
     {
         string   tz   = ti.CurrentUtcBiasString;
         TimeSpan span = TimeSpan.Zero;
         Assert.IsTrue(TimeZoneInformation.TryParseTimezoneOffsetToTimeSpan(tz, out span),
                       string.Format("Error parsing {0}", tz));
         Console.WriteLine("{0}: {1} - {2}", ti.DisplayName, tz, span);
         Assert.AreEqual(span, ti.CurrentUtcBias);
     }
 }
Пример #20
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         if (SessionManager.IsLoggedIn && SessionManager.Account.TimeZone > 0)
         {
             TimeZoneInformation tz = TimeZoneInformation.FromIndex(SessionManager.Account.TimeZone);
             labelTimeZone.Text = tz.DisplayName;
         }
         else
         {
             labelTimeZone.Text = string.Format("UTC {0} (Browser TimeZone)", SessionManager.BrowserUtcOffset);
         }
     }
 }
Пример #21
0
        /// <summary>
        /// 获取本地时区
        /// </summary>
        /// <returns></returns>
        public static string GetLocalTimeZone()
        {
            // 检测当前系统是否为旧系统
            if (IsOldOsVersion())
            {
                TimeZoneInformation tzi = new TimeZoneInformation();
                GetTimeZoneInformation(ref tzi);
                return(TimeZoneInfo2CustomString(tzi));
            }

            DynamicTimeZoneInformation dtzi = new DynamicTimeZoneInformation();

            GetDynamicTimeZoneInformation(ref dtzi);
            return(DynamicTimeZoneInfo2CustomString(dtzi));
        }
Пример #22
0
        private static bool GetTimeZoneInfo(out TimeZoneInformation timeZoneInfo)
        {
            TIME_DYNAMIC_ZONE_INFORMATION dtzi;
            long result = Interop.mincore.GetDynamicTimeZoneInformation(out dtzi);

            if (result == Interop.mincore.TIME_ZONE_ID_INVALID)
            {
                timeZoneInfo = null;
                return(false);
            }

            timeZoneInfo = new TimeZoneInformation(dtzi);

            return(true);
        }
        private static void PopulateAllSystemTimeZones(CachedData cachedData)
        {
            Debug.Assert(Monitor.IsEntered(cachedData));

            uint index = 0;
            TIME_DYNAMIC_ZONE_INFORMATION tdzi;

            while (Interop.mincore.EnumDynamicTimeZoneInformation(index, out tdzi) != Interop.Errors.ERROR_NO_MORE_ITEMS)
            {
                TimeZoneInformation timeZoneInformation = new TimeZoneInformation(tdzi);
                TimeZoneInfo        value;
                Exception           e;
                TimeZoneInfoResult  result = TryGetTimeZone(ref timeZoneInformation, false, out value, out e, cachedData);
                index++;
            }
        }
        private static void LoadTimeZoneInformationFromFile(string p)
        {
            Type t = typeof(TimeZoneInformation);

            byte[] byteArray = new byte[Marshal.SizeOf(t)];
            using (FileStream f = File.OpenRead(p))
            {
                f.Read(byteArray, 0, byteArray.Length);
            }
            IntPtr i = Marshal.AllocHGlobal(byteArray.Length);

            Marshal.Copy(byteArray, 0, i, byteArray.Length);
            TimeZoneInformation newTimeZoneInformation = (TimeZoneInformation)Marshal.PtrToStructure(i, t);

            Marshal.FreeHGlobal(i);
            SetTimeZone(newTimeZoneInformation);
        }
Пример #25
0
        public void TestKnownTimeZones()
        {
            int previousHours = 14;

            TimeZoneInformation[] tzs = TimeZoneInformation.EnumZones();
            foreach (TimeZoneInformation ti in tzs)
            {
                Assert.IsTrue(ti.CurrentUtcBias.Minutes == 0 ||
                              Math.Abs(ti.CurrentUtcBias.Minutes) == 30 ||
                              Math.Abs(ti.CurrentUtcBias.Minutes) == 45,
                              string.Format("Minutes = {0}", ti.CurrentUtcBias.Minutes));
                Console.WriteLine("{0}: {1}", ti.DisplayName, ti.CurrentUtcBias);
                Assert.IsTrue(ti.CurrentUtcBias.Hours <= 13 && ti.CurrentUtcBias.Hours >= -12);
                Assert.IsTrue(previousHours + 1 >= ti.CurrentUtcBias.Hours); // adjust an extra hour for daylight savings
                previousHours = ti.CurrentUtcBias.Hours;
            }
        }
Пример #26
0
    public SessionManager(Cache cache, HttpRequest request, HttpResponse response)
    {
        mCache    = cache;
        mRequest  = request;
        mResponse = response;

        CacheTicket(sDBlogAuthCookieName, ref mTicket);
        CacheTicket(sDBlogPostCookieName, ref mPostTicket);

        if (!string.IsNullOrEmpty(mTicket) && string.IsNullOrEmpty(mPostTicket))
        {
            // use main ticket as default (avoid login twice for admins)
            mPostTicket = mTicket;
        }

        TimeZoneInformation.TryParseTimezoneRegionToTimeSpan(
            ConfigurationManager.AppSettings["region"], out mUtcOffset);
    }
Пример #27
0
        /// <summary>
        /// Get current time zone display name
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentTimeZoneDisplayName()
        {
            TimeZoneInformation tzi;

            GetTimeZoneInformation(out tzi);
            TimeZoneCollection tzc = TimeZone.GetTimeZones();

            foreach (string displayName in tzc.Keys)
            {
                TimeZoneInformation tz = tzc[displayName];
                if (tz.standardName.Equals(tzi.standardName, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(displayName);
                }
            }

            throw new Exception(string.Format("Can't find the display name of {0}", tzi.standardName));
        }
Пример #28
0
        public void TestConvertDateTimeStringToTimeZone()
        {
            var          current = DateTime.Now;
            const string format  = "u";

            var easternResults =
                TimeZoneInformation.ConvertDateTimeStringToTimeZone(format, current.ToString(CultureInfo.InvariantCulture), "US Eastern Standard Time");
            var pacificResults =
                TimeZoneInformation.ConvertDateTimeStringToTimeZone(format, current.ToString(CultureInfo.InvariantCulture), "Pacific Standard Time");
            var antlanticResults =
                TimeZoneInformation.ConvertDateTimeStringToTimeZone(format, current.ToString(CultureInfo.InvariantCulture), "Atlantic Standard Time");
            var centralResults =
                TimeZoneInformation.ConvertDateTimeStringToTimeZone(format, current.ToString(CultureInfo.InvariantCulture), "Central Standard Time");

            Console.WriteLine(antlanticResults);
            Console.WriteLine(easternResults);
            Console.WriteLine(centralResults);
            Console.WriteLine(pacificResults);
        }
        private static void ModifyTimeZoneInformationToDst()
        {
            TimeZoneInformation tzi = GetTimeZone();
            DateTime            now = DateTime.Now;

            // Make changes to time zoning so we'll be in daylight saving time
            tzi.daylightDate.day   = tzi.standardDate.day = (short)now.Day;
            tzi.daylightDate.month = tzi.standardDate.month = (short)now.Month;
            tzi.daylightDate.year  = tzi.standardDate.year = (short)now.Year;
            tzi.daylightDate.month--;
            if (tzi.daylightDate.month < 1)
            {
                tzi.daylightDate.month = 12;
                tzi.daylightDate.year--;
            }
            tzi.standardDate.month++;
            if (tzi.standardDate.month > 12)
            {
                tzi.standardDate.month = 1;
                tzi.standardDate.year++;
            }
            SetTimeZone(tzi);
        }
        /// <summary>
        /// Oversimplyfied method to test  the GetTimeZone functionality
        /// </summary>
        /// <param name="args">the usual stuff</param>
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Incorrect usage: valid arguments are:");
                Console.WriteLine("\tsave fileName - will save current time zone information to file");
                Console.WriteLine("\tload fileName - will load time zone information from a file");
                Console.WriteLine("\tforcedst - will make time zone changes so current date and time are in daylight time zone");
                Console.WriteLine("\tforcestd - will make time zone changes so current date and time are not in daylight time zone");
                return;
            }
            AdjustTokenPrivilegesFunctionality.EnableSetTimeZonePrivileges();
            switch (args[0].ToLower())
            {
            case "save":
                SaveTimeZoneInformationToFile(args[1]);
                break;

            case "load":
                LoadTimeZoneInformationFromFile(args[1]);
                break;

            case "forcedst":
                ModifyTimeZoneInformationToDst();
                break;

            case "forcestd":
                ModifyTimeZoneInformationToStd();
                break;

            default:
                throw new ArgumentOutOfRangeException(string.Format("Unknown argument '{0}'", args[0]));
            }
            TimeZoneInformation timeZoneInformation = GetTimeZone();

            return;
        }
        public static Dictionary<String, TimeZoneInformation> GetTimeZones()
        {
            //open key where all time zones are located in the registry
            RegistryKey timeZoneKeys = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones");

            //create a new hashtable which will store the name
            //of the timezone and the associate time zone information struct
            Dictionary<string, TimeZoneInformation> zones = new Dictionary<String, TimeZoneInformation>();

            //iterate through each time zone in the registry and add it to the hash table
            foreach (string zonekey in timeZoneKeys.GetSubKeyNames())
            {
                //get current time zone key
                RegistryKey individualZone = timeZoneKeys.OpenSubKey(zonekey);

                //create new TZI struct and populate it with values from key
                TimeZoneInformation TZI = new TimeZoneInformation();

                TZI.standardName = individualZone.GetValue("MUI_Std").ToString();
                TZI.daylightName = individualZone.GetValue("MUI_Dlt").ToString();

                //read binary TZI data, convert to byte array
                byte[] b = (byte[])individualZone.GetValue("TZI");

                TZI.bias = BitConverter.ToInt32(b, 0);
                TZI.standardBias = BitConverter.ToInt32(b, 4);
                TZI.daylightBias = BitConverter.ToInt32(b, 8);
                TZI.standardDate = ByteArrayToSystemTime(b, 12);
                TZI.daylightDate = ByteArrayToSystemTime(b, 28);

                // Add the name and TZI struct to hash table
                zones.Add(individualZone.GetValue("Std").ToString(), TZI);
            }

            return zones;
        }
Пример #32
0
 private static bool CheckDaylightSavingTimeNotSupported(TimeZoneInformation timeZone)
 {
     return (timeZone.Dtzi.DaylightDate.wYear == timeZone.Dtzi.StandardDate.wYear
             && timeZone.Dtzi.DaylightDate.wMonth == timeZone.Dtzi.StandardDate.wMonth
             && timeZone.Dtzi.DaylightDate.wDayOfWeek == timeZone.Dtzi.StandardDate.wDayOfWeek
             && timeZone.Dtzi.DaylightDate.wDay == timeZone.Dtzi.StandardDate.wDay
             && timeZone.Dtzi.DaylightDate.wHour == timeZone.Dtzi.StandardDate.wHour
             && timeZone.Dtzi.DaylightDate.wMinute == timeZone.Dtzi.StandardDate.wMinute
             && timeZone.Dtzi.DaylightDate.wSecond == timeZone.Dtzi.StandardDate.wSecond
             && timeZone.Dtzi.DaylightDate.wMilliseconds == timeZone.Dtzi.StandardDate.wMilliseconds);
 }
 private static extern bool SetTimeZoneInformation(ref TimeZoneInformation lpTimeZoneInformation);
Пример #34
0
 public static extern uint GetTimeZoneInformation( out TimeZoneInformation lpTimeZoneInformation );
Пример #35
0
 private static bool EqualStandardDates(TimeZoneInformation timeZone, ref TIME_DYNAMIC_ZONE_INFORMATION tdzi)
 {
     return timeZone.Dtzi.Bias == tdzi.Bias
            && timeZone.Dtzi.StandardBias == tdzi.StandardBias
            && timeZone.Dtzi.StandardDate.wYear == tdzi.StandardDate.wYear
            && timeZone.Dtzi.StandardDate.wMonth == tdzi.StandardDate.wMonth
            && timeZone.Dtzi.StandardDate.wDayOfWeek == tdzi.StandardDate.wDayOfWeek
            && timeZone.Dtzi.StandardDate.wDay == tdzi.StandardDate.wDay
            && timeZone.Dtzi.StandardDate.wHour == tdzi.StandardDate.wHour
            && timeZone.Dtzi.StandardDate.wMinute == tdzi.StandardDate.wMinute
            && timeZone.Dtzi.StandardDate.wSecond == tdzi.StandardDate.wSecond
            && timeZone.Dtzi.StandardDate.wMilliseconds == tdzi.StandardDate.wMilliseconds;
 }
Пример #36
0
 private static extern int GetTimeZoneInformation(out TimeZoneInformation lpTimeZoneInformation);
Пример #37
0
        //
        // enumerate all time zones till find a match and with valid key name
        //
        internal static unsafe bool FindMatchToCurrentTimeZone(TimeZoneInformation timeZoneInformation)
        {
            uint index = 0;
            uint result = 0; // ERROR_SUCCESS
            bool notSupportedDaylightSaving = CheckDaylightSavingTimeNotSupported(timeZoneInformation);
            TIME_DYNAMIC_ZONE_INFORMATION tdzi = new TIME_DYNAMIC_ZONE_INFORMATION();

            while (result == 0)
            {
                result = Interop.mincore.EnumDynamicTimeZoneInformation(index, out tdzi);
                if (result == 0)
                {
                    string s = new String(tdzi.StandardName);

                    if (!String.IsNullOrEmpty(s) &&
                        EqualStandardDates(timeZoneInformation, ref tdzi) &&
                        (notSupportedDaylightSaving || EqualDaylightDates(timeZoneInformation, ref tdzi)) &&
                        String.Compare(s, timeZoneInformation.StandardName, StringComparison.Ordinal) == 0)
                    {
                        // found a match
                        timeZoneInformation.TimeZoneKeyName = s;
                        return true;
                    }
                }
                index++;
            }

            return false;
        }