6 * Stephane Delcroix <stephane@delcroix.org>
8 * Copyright 2011 Xamarin Inc.
10 * Permission is hereby granted, free of charge, to any person obtaining
11 * a copy of this software and associated documentation files (the
12 * "Software"), to deal in the Software without restriction, including
13 * without limitation the rights to use, copy, modify, merge, publish,
14 * distribute, sublicense, and/or sell copies of the Software, and to
15 * permit persons to whom the Software is furnished to do so, subject to
16 * the following conditions:
18 * The above copyright notice and this permission notice shall be
19 * included in all copies or substantial portions of the Software.
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Runtime.CompilerServices;
32 using System.Threading;
33 using System.Collections.Generic;
34 using System.Collections.ObjectModel;
35 using System.Runtime.Serialization;
37 using System.Globalization;
44 using Microsoft.Win32;
49 [TypeForwardedFrom (Consts.AssemblySystem_Core)]
51 [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
53 [SerializableAttribute]
55 sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
57 TimeSpan baseUtcOffset;
58 public TimeSpan BaseUtcOffset {
59 get { return baseUtcOffset; }
62 string daylightDisplayName;
63 public string DaylightName {
65 return supportsDaylightSavingTime
72 public string DisplayName {
73 get { return displayName; }
81 static TimeZoneInfo local;
82 public static TimeZoneInfo Local {
88 throw new TimeZoneNotFoundException ();
90 if (Interlocked.CompareExchange (ref local, l, null) != null)
99 TimeZone transitions are stored when there is a change on the base offset.
101 private List<KeyValuePair<DateTime, TimeType>> transitions;
103 static TimeZoneInfo CreateLocal ()
106 return AndroidTimeZones.Local;
108 using (Stream stream = GetMonoTouchData (null)) {
109 return BuildFromStream ("Local", stream);
113 if (IsWindows && LocalZoneKey != null) {
114 string name = (string)LocalZoneKey.GetValue ("TimeZoneKeyName");
116 name = (string)LocalZoneKey.GetValue ("StandardName"); // windows xp
117 name = TrimSpecial (name);
119 return TimeZoneInfo.FindSystemTimeZoneById (name);
123 var tz = Environment.GetEnvironmentVariable ("TZ");
125 if (tz == String.Empty)
128 return FindSystemTimeZoneByFileName (tz, Path.Combine (TimeZoneDirectory, tz));
135 return FindSystemTimeZoneByFileName ("Local", "/etc/localtime");
138 return FindSystemTimeZoneByFileName ("Local", Path.Combine (TimeZoneDirectory, "localtime"));
146 string standardDisplayName;
147 public string StandardName {
148 get { return standardDisplayName; }
151 bool supportsDaylightSavingTime;
152 public bool SupportsDaylightSavingTime {
153 get { return supportsDaylightSavingTime; }
156 static TimeZoneInfo utc;
157 public static TimeZoneInfo Utc {
160 utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
165 static string timeZoneDirectory;
166 static string TimeZoneDirectory {
168 if (timeZoneDirectory == null)
169 timeZoneDirectory = "/usr/share/zoneinfo";
170 return timeZoneDirectory;
174 timeZoneDirectory = value;
178 private AdjustmentRule [] adjustmentRules;
182 /// Determine whether windows of not (taken Stephane Delcroix's code)
184 private static bool IsWindows
187 int platform = (int) Environment.OSVersion.Platform;
188 return ((platform != 4) && (platform != 6) && (platform != 128));
193 /// Needed to trim misc garbage in MS registry keys
195 private static string TrimSpecial (string str)
200 while (Istart < str.Length && !char.IsLetterOrDigit(str[Istart])) Istart++;
201 var Iend = str.Length - 1;
202 while (Iend > Istart && !char.IsLetterOrDigit(str[Iend])) Iend--;
204 return str.Substring (Istart, Iend-Istart+1);
207 static RegistryKey timeZoneKey;
208 static RegistryKey TimeZoneKey {
210 if (timeZoneKey != null)
215 return timeZoneKey = Registry.LocalMachine.OpenSubKey (
216 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
221 static RegistryKey localZoneKey;
222 static RegistryKey LocalZoneKey {
224 if (localZoneKey != null)
230 return localZoneKey = Registry.LocalMachine.OpenSubKey (
231 "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation", false);
236 public static void ClearCachedData ()
240 systemTimeZones = null;
243 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
245 return ConvertTime (dateTime, dateTime.Kind == DateTimeKind.Utc ? TimeZoneInfo.Utc : TimeZoneInfo.Local, destinationTimeZone);
248 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
250 if (sourceTimeZone == null)
251 throw new ArgumentNullException ("sourceTimeZone");
253 if (destinationTimeZone == null)
254 throw new ArgumentNullException ("destinationTimeZone");
256 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
257 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
259 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
260 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
262 if (sourceTimeZone.IsInvalidTime (dateTime))
263 throw new ArgumentException ("dateTime parameter is an invalid time");
265 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
268 DateTime utc = ConvertTimeToUtc (dateTime, sourceTimeZone);
270 if (destinationTimeZone != TimeZoneInfo.Utc) {
271 utc = ConvertTimeFromUtc (utc, destinationTimeZone);
272 if (dateTime.Kind == DateTimeKind.Unspecified)
273 return DateTime.SpecifyKind (utc, DateTimeKind.Unspecified);
279 public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
281 if (destinationTimeZone == null)
282 throw new ArgumentNullException("destinationTimeZone");
284 var utcDateTime = dateTimeOffset.UtcDateTime;
287 var utcOffset = destinationTimeZone.GetUtcOffset(utcDateTime, out isDst);
289 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + utcOffset, utcOffset);
292 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
294 return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
297 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
299 return ConvertTime (dateTime, FindSystemTimeZoneById (sourceTimeZoneId), FindSystemTimeZoneById (destinationTimeZoneId));
302 public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
304 return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
307 private DateTime ConvertTimeFromUtc (DateTime dateTime)
309 if (dateTime.Kind == DateTimeKind.Local)
310 throw new ArgumentException ("Kind property of dateTime is Local");
312 if (this == TimeZoneInfo.Utc)
313 return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
315 var utcOffset = GetUtcOffset (dateTime);
317 var kind = (this == TimeZoneInfo.Local)? DateTimeKind.Local : DateTimeKind.Unspecified;
319 return DateTime.SpecifyKind (dateTime + utcOffset, kind);
322 public static DateTime ConvertTimeFromUtc (DateTime dateTime, TimeZoneInfo destinationTimeZone)
324 if (destinationTimeZone == null)
325 throw new ArgumentNullException ("destinationTimeZone");
327 return destinationTimeZone.ConvertTimeFromUtc (dateTime);
330 public static DateTime ConvertTimeToUtc (DateTime dateTime)
332 if (dateTime.Kind == DateTimeKind.Utc)
335 return ConvertTimeToUtc (dateTime, TimeZoneInfo.Local);
338 static internal DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags)
340 return ConvertTimeToUtc (dateTime, TimeZoneInfo.Local, flags);
343 public static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone)
345 return ConvertTimeToUtc (dateTime, sourceTimeZone, TimeZoneInfoOptions.None);
348 static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfoOptions flags)
350 if ((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) {
351 if (sourceTimeZone == null)
352 throw new ArgumentNullException ("sourceTimeZone");
354 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
355 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
357 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
358 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
360 if (sourceTimeZone.IsInvalidTime (dateTime))
361 throw new ArgumentException ("dateTime parameter is an invalid time");
364 if (dateTime.Kind == DateTimeKind.Utc)
368 var utcOffset = sourceTimeZone.GetUtcOffset (dateTime, out isDst);
370 return DateTime.SpecifyKind (dateTime - utcOffset, DateTimeKind.Utc);
373 static internal TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out Boolean isAmbiguousLocalDst)
375 bool isDaylightSavings;
376 return GetUtcOffsetFromUtc(time, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst);
379 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName)
381 return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
384 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
386 return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
389 public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
391 return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
394 public override bool Equals (object obj)
396 return Equals (obj as TimeZoneInfo);
399 public bool Equals (TimeZoneInfo other)
404 return other.Id == this.Id && HasSameRules (other);
407 public static TimeZoneInfo FindSystemTimeZoneById (string id)
409 //FIXME: this method should check for cached values in systemTimeZones
411 throw new ArgumentNullException ("id");
413 if (TimeZoneKey != null)
415 if (id == "Coordinated Universal Time")
416 id = "UTC"; //windows xp exception for "StandardName" property
417 RegistryKey key = TimeZoneKey.OpenSubKey (id, false);
419 throw new TimeZoneNotFoundException ();
420 return FromRegistryKey(id, key);
423 // Local requires special logic that already exists in the Local property (bug #326)
427 using (Stream stream = GetMonoTouchData (id)) {
428 return BuildFromStream (id, stream);
431 var timeZoneInfo = AndroidTimeZones.GetTimeZone (id, id);
432 if (timeZoneInfo == null)
433 throw new TimeZoneNotFoundException ();
436 string filepath = Path.Combine (TimeZoneDirectory, id);
437 return FindSystemTimeZoneByFileName (id, filepath);
439 throw new NotImplementedException ();
444 private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
446 if (!File.Exists (filepath))
447 throw new TimeZoneNotFoundException ();
449 using (FileStream stream = File.OpenRead (filepath)) {
450 return BuildFromStream (id, stream);
454 #if LIBC || MONOTOUCH
455 const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
457 private static TimeZoneInfo BuildFromStream (string id, Stream stream)
459 byte [] buffer = new byte [BUFFER_SIZE];
460 int length = stream.Read (buffer, 0, BUFFER_SIZE);
462 if (!ValidTZFile (buffer, length))
463 throw new InvalidTimeZoneException ("TZ file too big for the buffer");
466 return ParseTZBuffer (id, buffer, length);
467 } catch (Exception e) {
468 throw new InvalidTimeZoneException (e.Message);
474 private static TimeZoneInfo FromRegistryKey (string id, RegistryKey key)
476 byte [] reg_tzi = (byte []) key.GetValue ("TZI");
479 throw new InvalidTimeZoneException ();
481 int bias = BitConverter.ToInt32 (reg_tzi, 0);
482 TimeSpan baseUtcOffset = new TimeSpan (0, -bias, 0);
484 string display_name = (string) key.GetValue ("Display");
485 string standard_name = (string) key.GetValue ("Std");
486 string daylight_name = (string) key.GetValue ("Dlt");
488 List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
490 RegistryKey dst_key = key.OpenSubKey ("Dynamic DST", false);
491 if (dst_key != null) {
492 int first_year = (int) dst_key.GetValue ("FirstEntry");
493 int last_year = (int) dst_key.GetValue ("LastEntry");
496 for (year=first_year; year<=last_year; year++) {
497 byte [] dst_tzi = (byte []) dst_key.GetValue (year.ToString ());
498 if (dst_tzi != null) {
499 int start_year = year == first_year ? 1 : year;
500 int end_year = year == last_year ? 9999 : year;
501 ParseRegTzi(adjustmentRules, start_year, end_year, dst_tzi);
506 ParseRegTzi(adjustmentRules, 1, 9999, reg_tzi);
508 return CreateCustomTimeZone (id, baseUtcOffset, display_name, standard_name, daylight_name, ValidateRules (adjustmentRules).ToArray ());
511 private static void ParseRegTzi (List<AdjustmentRule> adjustmentRules, int start_year, int end_year, byte [] buffer)
513 //int standard_bias = BitConverter.ToInt32 (buffer, 4); /* not sure how to handle this */
514 int daylight_bias = BitConverter.ToInt32 (buffer, 8);
516 int standard_year = BitConverter.ToInt16 (buffer, 12);
517 int standard_month = BitConverter.ToInt16 (buffer, 14);
518 int standard_dayofweek = BitConverter.ToInt16 (buffer, 16);
519 int standard_day = BitConverter.ToInt16 (buffer, 18);
520 int standard_hour = BitConverter.ToInt16 (buffer, 20);
521 int standard_minute = BitConverter.ToInt16 (buffer, 22);
522 int standard_second = BitConverter.ToInt16 (buffer, 24);
523 int standard_millisecond = BitConverter.ToInt16 (buffer, 26);
525 int daylight_year = BitConverter.ToInt16 (buffer, 28);
526 int daylight_month = BitConverter.ToInt16 (buffer, 30);
527 int daylight_dayofweek = BitConverter.ToInt16 (buffer, 32);
528 int daylight_day = BitConverter.ToInt16 (buffer, 34);
529 int daylight_hour = BitConverter.ToInt16 (buffer, 36);
530 int daylight_minute = BitConverter.ToInt16 (buffer, 38);
531 int daylight_second = BitConverter.ToInt16 (buffer, 40);
532 int daylight_millisecond = BitConverter.ToInt16 (buffer, 42);
534 if (standard_month == 0 || daylight_month == 0)
538 DateTime start_timeofday = new DateTime (1, 1, 1, daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
539 TransitionTime start_transition_time;
541 if (daylight_year == 0) {
542 start_date = new DateTime (start_year, 1, 1);
543 start_transition_time = TransitionTime.CreateFloatingDateRule (
544 start_timeofday, daylight_month, daylight_day,
545 (DayOfWeek) daylight_dayofweek);
548 start_date = new DateTime (daylight_year, daylight_month, daylight_day,
549 daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
550 start_transition_time = TransitionTime.CreateFixedDateRule (
551 start_timeofday, daylight_month, daylight_day);
555 DateTime end_timeofday = new DateTime (1, 1, 1, standard_hour, standard_minute, standard_second, standard_millisecond);
556 TransitionTime end_transition_time;
558 if (standard_year == 0) {
559 end_date = new DateTime (end_year, 12, 31);
560 end_transition_time = TransitionTime.CreateFloatingDateRule (
561 end_timeofday, standard_month, standard_day,
562 (DayOfWeek) standard_dayofweek);
565 end_date = new DateTime (standard_year, standard_month, standard_day,
566 standard_hour, standard_minute, standard_second, standard_millisecond);
567 end_transition_time = TransitionTime.CreateFixedDateRule (
568 end_timeofday, standard_month, standard_day);
571 TimeSpan daylight_delta = new TimeSpan(0, -daylight_bias, 0);
573 adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (
574 start_date, end_date, daylight_delta,
575 start_transition_time, end_transition_time));
579 public AdjustmentRule [] GetAdjustmentRules ()
581 if (!supportsDaylightSavingTime)
582 return new AdjustmentRule [0];
584 return (AdjustmentRule []) adjustmentRules.Clone ();
587 public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
589 if (!IsAmbiguousTime (dateTime))
590 throw new ArgumentException ("dateTime is not an ambiguous time");
592 AdjustmentRule rule = GetApplicableRule (dateTime);
594 return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
596 return new TimeSpan[] {baseUtcOffset, baseUtcOffset};
599 public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
601 if (!IsAmbiguousTime (dateTimeOffset))
602 throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
604 throw new NotImplementedException ();
607 public override int GetHashCode ()
609 int hash_code = Id.GetHashCode ();
610 foreach (AdjustmentRule rule in GetAdjustmentRules ())
611 hash_code ^= rule.GetHashCode ();
615 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
618 throw new ArgumentNullException ("info");
619 info.AddValue ("Id", id);
620 info.AddValue ("DisplayName", displayName);
621 info.AddValue ("StandardName", standardDisplayName);
622 info.AddValue ("DaylightName", daylightDisplayName);
623 info.AddValue ("BaseUtcOffset", baseUtcOffset);
624 info.AddValue ("AdjustmentRules", adjustmentRules);
625 info.AddValue ("SupportsDaylightSavingTime", SupportsDaylightSavingTime);
628 //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
629 private static List<TimeZoneInfo> systemTimeZones;
630 public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
632 if (systemTimeZones == null) {
633 systemTimeZones = new List<TimeZoneInfo> ();
635 if (TimeZoneKey != null) {
636 foreach (string id in TimeZoneKey.GetSubKeyNames ()) {
638 systemTimeZones.Add (FindSystemTimeZoneById (id));
642 return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
646 foreach (string id in AndroidTimeZones.GetAvailableIds ()) {
647 var tz = AndroidTimeZones.GetTimeZone (id, id);
649 systemTimeZones.Add (tz);
652 if (systemTimeZones.Count == 0) {
653 foreach (string name in GetMonoTouchNames ()) {
654 using (Stream stream = GetMonoTouchData (name, false)) {
657 systemTimeZones.Add (BuildFromStream (name, stream));
662 string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
663 foreach (string continent in continents) {
665 foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
667 string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
668 systemTimeZones.Add (FindSystemTimeZoneById (id));
669 } catch (ArgumentNullException) {
670 } catch (TimeZoneNotFoundException) {
671 } catch (InvalidTimeZoneException) {
672 } catch (Exception) {
679 throw new NotImplementedException ("This method is not implemented for this platform");
682 return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
685 public TimeSpan GetUtcOffset (DateTime dateTime)
688 return GetUtcOffset (dateTime, out isDST);
691 public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
693 throw new NotImplementedException ();
696 private TimeSpan GetUtcOffset (DateTime dateTime, out bool isDST)
700 TimeZoneInfo tz = this;
701 if (dateTime.Kind == DateTimeKind.Utc)
702 tz = TimeZoneInfo.Utc;
704 if (dateTime.Kind == DateTimeKind.Local)
705 tz = TimeZoneInfo.Local;
708 var tzOffset = GetUtcOffset (dateTime, tz, out isTzDst);
715 var utcTicks = dateTime.Ticks - tzOffset.Ticks;
716 if (utcTicks < 0 || utcTicks > DateTime.MaxValue.Ticks)
717 return BaseUtcOffset;
719 var utcDateTime = new DateTime (utcTicks, DateTimeKind.Utc);
721 return GetUtcOffset (utcDateTime, this, out isDST);
724 private static TimeSpan GetUtcOffset (DateTime dateTime, TimeZoneInfo tz, out bool isDST)
726 if (dateTime.Kind == DateTimeKind.Local && tz != TimeZoneInfo.Local)
727 throw new Exception ();
731 if (tz == TimeZoneInfo.Utc)
732 return TimeSpan.Zero;
735 if (tz.TryGetTransitionOffset(dateTime, out offset, out isDST))
738 if (dateTime.Kind == DateTimeKind.Utc) {
739 var utcRule = tz.GetApplicableRule (dateTime);
740 if (utcRule != null && tz.IsInDST (utcRule, dateTime)) {
742 return tz.BaseUtcOffset + utcRule.DaylightDelta;
745 return tz.BaseUtcOffset;
748 var stdTicks = dateTime.Ticks - tz.BaseUtcOffset.Ticks;
749 if (stdTicks < 0 || stdTicks > DateTime.MaxValue.Ticks)
750 return tz.BaseUtcOffset;
752 var stdUtcDateTime = new DateTime (stdTicks, DateTimeKind.Utc);
753 var tzRule = tz.GetApplicableRule (stdUtcDateTime);
755 DateTime dstUtcDateTime = DateTime.MinValue;
756 if (tzRule != null) {
757 var dstTicks = stdUtcDateTime.Ticks - tzRule.DaylightDelta.Ticks;
758 if (dstTicks < 0 || dstTicks > DateTime.MaxValue.Ticks)
759 return tz.BaseUtcOffset;
761 dstUtcDateTime = new DateTime (dstTicks, DateTimeKind.Utc);
764 if (tzRule != null && tz.IsInDST (tzRule, stdUtcDateTime) && tz.IsInDST (tzRule, dstUtcDateTime)) {
766 return tz.BaseUtcOffset + tzRule.DaylightDelta;
769 return tz.BaseUtcOffset;
772 public bool HasSameRules (TimeZoneInfo other)
775 throw new ArgumentNullException ("other");
777 if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
780 if (this.adjustmentRules == null)
783 if (this.BaseUtcOffset != other.BaseUtcOffset)
786 if (this.adjustmentRules.Length != other.adjustmentRules.Length)
789 for (int i = 0; i < adjustmentRules.Length; i++) {
790 if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
797 public bool IsAmbiguousTime (DateTime dateTime)
799 if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
800 throw new ArgumentException ("Kind is Local and time is Invalid");
802 if (this == TimeZoneInfo.Utc)
805 if (dateTime.Kind == DateTimeKind.Utc)
806 dateTime = ConvertTimeFromUtc (dateTime);
808 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
809 dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
811 AdjustmentRule rule = GetApplicableRule (dateTime);
813 DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
814 if (dateTime > tpoint - rule.DaylightDelta && dateTime <= tpoint)
821 public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
823 throw new NotImplementedException ();
826 private bool IsInDST (AdjustmentRule rule, DateTime dateTime)
828 // Check whether we're in the dateTime year's DST period
829 if (IsInDSTForYear (rule, dateTime, dateTime.Year))
832 // We might be in the dateTime previous year's DST period
833 return IsInDSTForYear (rule, dateTime, dateTime.Year - 1);
836 bool IsInDSTForYear (AdjustmentRule rule, DateTime dateTime, int year)
838 DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, year);
839 DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
840 if (dateTime.Kind == DateTimeKind.Utc) {
841 DST_start -= BaseUtcOffset;
842 DST_end -= (BaseUtcOffset + rule.DaylightDelta);
845 return (dateTime >= DST_start && dateTime < DST_end);
848 public bool IsDaylightSavingTime (DateTime dateTime)
850 if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
851 throw new ArgumentException ("dateTime is invalid and Kind is Local");
853 if (this == TimeZoneInfo.Utc)
856 if (!SupportsDaylightSavingTime)
860 GetUtcOffset (dateTime, out isDst);
865 internal bool IsDaylightSavingTime (DateTime dateTime, TimeZoneInfoOptions flags)
867 return IsDaylightSavingTime (dateTime);
870 public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
872 throw new NotImplementedException ();
875 void IDeserializationCallback.OnDeserialization (object sender)
878 TimeZoneInfo.Validate (id, baseUtcOffset, adjustmentRules);
879 } catch (ArgumentException ex) {
880 throw new SerializationException ("invalid serialization data", ex);
884 private static void Validate (string id, TimeSpan baseUtcOffset, AdjustmentRule [] adjustmentRules)
887 throw new ArgumentNullException ("id");
889 if (id == String.Empty)
890 throw new ArgumentException ("id parameter is an empty string");
892 if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
893 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
895 if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
896 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
900 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
903 if (adjustmentRules != null && adjustmentRules.Length != 0) {
904 AdjustmentRule prev = null;
905 foreach (AdjustmentRule current in adjustmentRules) {
907 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
909 if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
910 (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
911 throw new InvalidTimeZoneException ("Sum of baseUtcOffset and DaylightDelta of one or more object in adjustmentRules array is greater than 14 or less than -14 hours;");
913 if (prev != null && prev.DateStart > current.DateStart)
914 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
916 if (prev != null && prev.DateEnd > current.DateStart)
917 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
919 if (prev != null && prev.DateEnd == current.DateStart)
920 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
927 public override string ToString ()
932 private TimeZoneInfo (SerializationInfo info, StreamingContext context)
935 throw new ArgumentNullException ("info");
936 id = (string) info.GetValue ("Id", typeof (string));
937 displayName = (string) info.GetValue ("DisplayName", typeof (string));
938 standardDisplayName = (string) info.GetValue ("StandardName", typeof (string));
939 daylightDisplayName = (string) info.GetValue ("DaylightName", typeof (string));
940 baseUtcOffset = (TimeSpan) info.GetValue ("BaseUtcOffset", typeof (TimeSpan));
941 adjustmentRules = (TimeZoneInfo.AdjustmentRule []) info.GetValue ("AdjustmentRules", typeof (TimeZoneInfo.AdjustmentRule []));
942 supportsDaylightSavingTime = (bool) info.GetValue ("SupportsDaylightSavingTime", typeof (bool));
945 private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
948 throw new ArgumentNullException ("id");
950 if (id == String.Empty)
951 throw new ArgumentException ("id parameter is an empty string");
953 if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
954 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
956 if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
957 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
961 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
964 bool supportsDaylightSavingTime = !disableDaylightSavingTime;
966 if (adjustmentRules != null && adjustmentRules.Length != 0) {
967 AdjustmentRule prev = null;
968 foreach (AdjustmentRule current in adjustmentRules) {
970 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
972 if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
973 (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
974 throw new InvalidTimeZoneException ("Sum of baseUtcOffset and DaylightDelta of one or more object in adjustmentRules array is greater than 14 or less than -14 hours;");
976 if (prev != null && prev.DateStart > current.DateStart)
977 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
979 if (prev != null && prev.DateEnd > current.DateStart)
980 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
982 if (prev != null && prev.DateEnd == current.DateStart)
983 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
988 supportsDaylightSavingTime = false;
992 this.baseUtcOffset = baseUtcOffset;
993 this.displayName = displayName ?? id;
994 this.standardDisplayName = standardDisplayName ?? id;
995 this.daylightDisplayName = daylightDisplayName;
996 this.supportsDaylightSavingTime = supportsDaylightSavingTime;
997 this.adjustmentRules = adjustmentRules;
1000 private AdjustmentRule GetApplicableRule (DateTime dateTime)
1002 //Applicable rules are in standard time
1003 DateTime date = dateTime;
1005 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
1006 date = date.ToUniversalTime () + BaseUtcOffset;
1007 else if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
1008 date = date + BaseUtcOffset;
1010 // get the date component of the datetime
1013 if (adjustmentRules != null) {
1014 foreach (AdjustmentRule rule in adjustmentRules) {
1015 if (rule.DateStart > date)
1017 if (rule.DateEnd < date)
1025 private bool TryGetTransitionOffset (DateTime dateTime, out TimeSpan offset,out bool isDst)
1027 offset = BaseUtcOffset;
1030 if (transitions == null)
1033 //Transitions are in UTC
1034 DateTime date = dateTime;
1036 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local) {
1037 var ticks = date.ToUniversalTime ().Ticks + BaseUtcOffset.Ticks;
1038 if (ticks < DateTime.MinValue.Ticks || ticks > DateTime.MaxValue.Ticks)
1041 date = new DateTime (ticks, DateTimeKind.Utc);
1044 if (dateTime.Kind != DateTimeKind.Utc) {
1045 var ticks = date.Ticks - BaseUtcOffset.Ticks;
1046 if (ticks < DateTime.MinValue.Ticks || ticks > DateTime.MaxValue.Ticks)
1049 date = new DateTime (ticks, DateTimeKind.Utc);
1052 for (var i = transitions.Count - 1; i >= 0; i--) {
1053 var pair = transitions [i];
1054 DateTime ttime = pair.Key;
1055 TimeType ttype = pair.Value;
1060 offset = new TimeSpan (0, 0, ttype.Offset);
1061 isDst = ttype.IsDst;
1069 private static DateTime TransitionPoint (TransitionTime transition, int year)
1071 if (transition.IsFixedDateRule)
1072 return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
1074 DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
1075 int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first + 7) % 7;
1076 if (day > DateTime.DaysInMonth (year, transition.Month))
1080 return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
1083 static List<AdjustmentRule> ValidateRules (List<AdjustmentRule> adjustmentRules)
1085 AdjustmentRule prev = null;
1086 foreach (AdjustmentRule current in adjustmentRules.ToArray ()) {
1087 if (prev != null && prev.DateEnd > current.DateStart) {
1088 adjustmentRules.Remove (current);
1092 return adjustmentRules;
1095 #if LIBC || MONODROID
1096 private static bool ValidTZFile (byte [] buffer, int length)
1098 StringBuilder magic = new StringBuilder ();
1100 for (int i = 0; i < 4; i++)
1101 magic.Append ((char)buffer [i]);
1103 if (magic.ToString () != "TZif")
1106 if (length >= BUFFER_SIZE)
1112 static int SwapInt32 (int i)
1114 return (((i >> 24) & 0xff)
1115 | ((i >> 8) & 0xff00)
1116 | ((i << 8) & 0xff0000)
1120 static int ReadBigEndianInt32 (byte [] buffer, int start)
1122 int i = BitConverter.ToInt32 (buffer, start);
1123 if (!BitConverter.IsLittleEndian)
1126 return SwapInt32 (i);
1129 private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
1131 //Reading the header. 4 bytes for magic, 16 are reserved
1132 int ttisgmtcnt = ReadBigEndianInt32 (buffer, 20);
1133 int ttisstdcnt = ReadBigEndianInt32 (buffer, 24);
1134 int leapcnt = ReadBigEndianInt32 (buffer, 28);
1135 int timecnt = ReadBigEndianInt32 (buffer, 32);
1136 int typecnt = ReadBigEndianInt32 (buffer, 36);
1137 int charcnt = ReadBigEndianInt32 (buffer, 40);
1139 if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
1140 throw new InvalidTimeZoneException ();
1142 Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
1143 Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
1144 List<KeyValuePair<DateTime, TimeType>> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
1146 if (time_types.Count == 0)
1147 throw new InvalidTimeZoneException ();
1149 if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
1150 throw new InvalidTimeZoneException ();
1152 TimeSpan baseUtcOffset = new TimeSpan (0);
1153 TimeSpan dstDelta = new TimeSpan (0);
1154 string standardDisplayName = null;
1155 string daylightDisplayName = null;
1156 bool dst_observed = false;
1157 DateTime dst_start = DateTime.MinValue;
1158 List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
1159 bool storeTransition = false;
1161 for (int i = 0; i < transitions.Count; i++) {
1162 var pair = transitions [i];
1163 DateTime ttime = pair.Key;
1164 TimeType ttype = pair.Value;
1166 if (standardDisplayName != ttype.Name)
1167 standardDisplayName = ttype.Name;
1168 if (baseUtcOffset.TotalSeconds != ttype.Offset) {
1169 baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
1170 if (adjustmentRules.Count > 0) // We ignore AdjustmentRules but store transitions.
1171 storeTransition = true;
1172 adjustmentRules = new List<AdjustmentRule> ();
1173 dst_observed = false;
1176 //FIXME: check additional fields for this:
1177 //most of the transitions are expressed in GMT
1178 dst_start += baseUtcOffset;
1179 DateTime dst_end = ttime + baseUtcOffset + dstDelta;
1181 //some weird timezone (America/Phoenix) have end dates on Jan 1st
1182 if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
1183 dst_end -= new TimeSpan (24, 0, 0);
1185 DateTime dateStart, dateEnd;
1186 if (dst_start.Month < 7)
1187 dateStart = new DateTime (dst_start.Year, 1, 1);
1189 dateStart = new DateTime (dst_start.Year, 7, 1);
1191 if (dst_end.Month >= 7)
1192 dateEnd = new DateTime (dst_end.Year, 12, 31);
1194 dateEnd = new DateTime (dst_end.Year, 6, 30);
1197 TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
1198 TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
1199 if (transition_start != transition_end) //y, that happened in Argentina in 1943-1946
1200 adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
1202 dst_observed = false;
1204 if (daylightDisplayName != ttype.Name)
1205 daylightDisplayName = ttype.Name;
1206 if (dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds)
1207 dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
1210 dst_observed = true;
1215 if (adjustmentRules.Count == 0 && !storeTransition) {
1216 TimeType t = (TimeType)time_types [0];
1217 if (standardDisplayName == null) {
1218 standardDisplayName = t.Name;
1219 baseUtcOffset = new TimeSpan (0, 0, t.Offset);
1221 tz = CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
1223 tz = CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, ValidateRules (adjustmentRules).ToArray ());
1226 if (storeTransition)
1227 tz.transitions = transitions;
1232 static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
1234 var abbrevs = new Dictionary<int, string> ();
1235 int abbrev_index = 0;
1236 var sb = new StringBuilder ();
1237 for (int i = 0; i < count; i++) {
1238 char c = (char) buffer [index + i];
1242 abbrevs.Add (abbrev_index, sb.ToString ());
1243 //Adding all the substrings too, as it seems to be used, at least for Africa/Windhoek
1244 for (int j = 1; j < sb.Length; j++)
1245 abbrevs.Add (abbrev_index + j, sb.ToString (j, sb.Length - j));
1246 abbrev_index = i + 1;
1247 sb = new StringBuilder ();
1253 static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
1255 var types = new Dictionary<int, TimeType> (count);
1256 for (int i = 0; i < count; i++) {
1257 int offset = ReadBigEndianInt32 (buffer, index + 6 * i);
1258 byte is_dst = buffer [index + 6 * i + 4];
1259 byte abbrev = buffer [index + 6 * i + 5];
1260 types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
1265 static List<KeyValuePair<DateTime, TimeType>> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
1267 var list = new List<KeyValuePair<DateTime, TimeType>> (count);
1268 for (int i = 0; i < count; i++) {
1269 int unixtime = ReadBigEndianInt32 (buffer, index + 4 * i);
1270 DateTime ttime = DateTimeFromUnixTime (unixtime);
1271 byte ttype = buffer [index + 4 * count + i];
1272 list.Add (new KeyValuePair<DateTime, TimeType> (ttime, time_types [(int)ttype]));
1277 static DateTime DateTimeFromUnixTime (long unix_time)
1279 DateTime date_time = new DateTime (1970, 1, 1);
1280 return date_time.AddSeconds (unix_time);
1283 #region reference sources
1284 // Shortcut for TimeZoneInfo.Local.GetUtcOffset
1285 internal static TimeSpan GetLocalUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags)
1288 return Local.GetUtcOffset (dateTime, out dst);
1291 internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags)
1294 return GetUtcOffset (dateTime, out dst);
1297 // used by GetUtcOffsetFromUtc (DateTime.Now, DateTime.ToLocalTime) for max/min whole-day range checks
1298 private static DateTime s_maxDateOnly = new DateTime(9999, 12, 31);
1299 private static DateTime s_minDateOnly = new DateTime(1, 1, 2);
1301 static internal TimeSpan GetUtcOffsetFromUtc (DateTime time, TimeZoneInfo zone, out Boolean isDaylightSavings, out Boolean isAmbiguousLocalDst)
1303 isDaylightSavings = false;
1304 isAmbiguousLocalDst = false;
1305 TimeSpan baseOffset = zone.BaseUtcOffset;
1307 AdjustmentRule rule;
1309 if (time > s_maxDateOnly) {
1310 rule = zone.GetAdjustmentRuleForTime(DateTime.MaxValue);
1313 else if (time < s_minDateOnly) {
1314 rule = zone.GetAdjustmentRuleForTime(DateTime.MinValue);
1318 DateTime targetTime = time + baseOffset;
1320 rule = zone.GetAdjustmentRuleForTime(targetTime);
1324 isDaylightSavings = GetIsDaylightSavingsFromUtc(time, year, zone.baseUtcOffset, rule, out isAmbiguousLocalDst);
1325 baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* */);
1331 // assumes dateTime is in the current time zone's time
1332 private AdjustmentRule GetAdjustmentRuleForTime(DateTime dateTime) {
1333 if (adjustmentRules == null || adjustmentRules.Length == 0) {
1337 #if WINXP_AND_WIN2K3_SUPPORT
1338 // On pre-Vista versions of Windows if you run "cmd /c date" or "cmd /c time" to update the system time
1339 // the operating system doesn't pick up the correct time zone adjustment rule (it stays on the currently loaded rule).
1340 // We need to use the OS API data in this scenario instead of the loaded adjustment rules from the registry for
1341 // consistency. Otherwise DateTime.Now might not match the time displayed in the system tray.
1342 if (!Environment.IsWindowsVistaOrAbove && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local) {
1343 return s_cachedData.GetOneYearLocalFromLocal(dateTime.Year).rule;
1346 // Only check the whole-date portion of the dateTime -
1347 // This is because the AdjustmentRule DateStart & DateEnd are stored as
1348 // Date-only values {4/2/2006 - 10/28/2006} but actually represent the
1349 // time span {4/2/2006@00:00:00.00000 - 10/28/2006@23:59:59.99999}
1350 DateTime date = dateTime.Date;
1352 for (int i = 0; i < adjustmentRules.Length; i++) {
1353 if (adjustmentRules[i].DateStart <= date && adjustmentRules[i].DateEnd >= date) {
1354 return adjustmentRules[i];
1362 // GetIsDaylightSavingsFromUtc -
1364 // Helper function that checks if a given dateTime is in Daylight Saving Time (DST)
1365 // This function assumes the dateTime is in UTC and AdjustmentRule is in a different time zone
1367 static private Boolean GetIsDaylightSavingsFromUtc(DateTime time, Int32 Year, TimeSpan utc, AdjustmentRule rule, out Boolean isAmbiguousLocalDst) {
1368 isAmbiguousLocalDst = false;
1374 // Get the daylight changes for the year of the specified time.
1375 TimeSpan offset = utc; /* */
1376 DaylightTime daylightTime = GetDaylightTime(Year, rule);
1378 // The start and end times represent the range of universal times that are in DST for that year.
1379 // Within that there is an ambiguous hour, usually right at the end, but at the beginning in
1380 // the unusual case of a negative daylight savings delta.
1381 DateTime startTime = daylightTime.Start - offset;
1382 DateTime endTime = daylightTime.End - offset - rule.DaylightDelta; /* */
1383 DateTime ambiguousStart;
1384 DateTime ambiguousEnd;
1385 if (daylightTime.Delta.Ticks > 0) {
1386 ambiguousStart = endTime - daylightTime.Delta;
1387 ambiguousEnd = endTime;
1389 ambiguousStart = startTime;
1390 ambiguousEnd = startTime - daylightTime.Delta;
1393 Boolean isDst = CheckIsDst(startTime, time, endTime);
1395 // See if the resulting local time becomes ambiguous. This must be captured here or the
1396 // DateTime will not be able to round-trip back to UTC accurately.
1398 isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
1400 if (!isAmbiguousLocalDst && ambiguousStart.Year != ambiguousEnd.Year) {
1401 // there exists an extreme corner case where the start or end period is on a year boundary and
1402 // because of this the comparison above might have been performed for a year-early or a year-later
1403 // than it should have been.
1404 DateTime ambiguousStartModified;
1405 DateTime ambiguousEndModified;
1407 ambiguousStartModified = ambiguousStart.AddYears(1);
1408 ambiguousEndModified = ambiguousEnd.AddYears(1);
1409 isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
1411 catch (ArgumentOutOfRangeException) {}
1413 if (!isAmbiguousLocalDst) {
1415 ambiguousStartModified = ambiguousStart.AddYears(-1);
1416 ambiguousEndModified = ambiguousEnd.AddYears(-1);
1417 isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
1419 catch (ArgumentOutOfRangeException) {}
1429 static private Boolean CheckIsDst(DateTime startTime, DateTime time, DateTime endTime) {
1432 int startTimeYear = startTime.Year;
1433 int endTimeYear = endTime.Year;
1435 if (startTimeYear != endTimeYear) {
1436 endTime = endTime.AddYears(startTimeYear - endTimeYear);
1439 int timeYear = time.Year;
1441 if (startTimeYear != timeYear) {
1442 time = time.AddYears(startTimeYear - timeYear);
1445 if (startTime > endTime) {
1446 // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year.
1447 // Note, the summer in the southern hemisphere begins late in the year.
1448 isDst = (time < endTime || time >= startTime);
1451 // In northern hemisphere, the daylight saving time starts in the middle of the year.
1452 isDst = (time >= startTime && time < endTime);
1458 // GetDaylightTime -
1460 // Helper function that returns a DaylightTime from a year and AdjustmentRule
1462 static private DaylightTime GetDaylightTime(Int32 year, AdjustmentRule rule) {
1463 TimeSpan delta = rule.DaylightDelta;
1464 DateTime startTime = TransitionTimeToDateTime(year, rule.DaylightTransitionStart);
1465 DateTime endTime = TransitionTimeToDateTime(year, rule.DaylightTransitionEnd);
1466 return new DaylightTime(startTime, endTime, delta);
1470 // TransitionTimeToDateTime -
1472 // Helper function that converts a year and TransitionTime into a DateTime
1474 static private DateTime TransitionTimeToDateTime(Int32 year, TransitionTime transitionTime) {
1476 DateTime timeOfDay = transitionTime.TimeOfDay;
1478 if (transitionTime.IsFixedDateRule) {
1479 // create a DateTime from the passed in year and the properties on the transitionTime
1481 // if the day is out of range for the month then use the last day of the month
1482 Int32 day = DateTime.DaysInMonth(year, transitionTime.Month);
1484 value = new DateTime(year, transitionTime.Month, (day < transitionTime.Day) ? day : transitionTime.Day,
1485 timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
1488 if (transitionTime.Week <= 4) {
1490 // Get the (transitionTime.Week)th Sunday.
1492 value = new DateTime(year, transitionTime.Month, 1,
1493 timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
1495 int dayOfWeek = (int)value.DayOfWeek;
1496 int delta = (int)transitionTime.DayOfWeek - dayOfWeek;
1500 delta += 7 * (transitionTime.Week - 1);
1503 value = value.AddDays(delta);
1508 // If TransitionWeek is greater than 4, we will get the last week.
1510 Int32 daysInMonth = DateTime.DaysInMonth(year, transitionTime.Month);
1511 value = new DateTime(year, transitionTime.Month, daysInMonth,
1512 timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
1514 // This is the day of week for the last day of the month.
1515 int dayOfWeek = (int)value.DayOfWeek;
1516 int delta = dayOfWeek - (int)transitionTime.DayOfWeek;
1522 value = value.AddDays(-delta);
1532 // returns true when dateTime falls into a "hole in time".
1534 public Boolean IsInvalidTime(DateTime dateTime) {
1535 Boolean isInvalid = false;
1537 if ( (dateTime.Kind == DateTimeKind.Unspecified)
1538 || (dateTime.Kind == DateTimeKind.Local && this == Local) ) {
1540 // only check Unspecified and (Local when this TimeZoneInfo instance is Local)
1541 AdjustmentRule rule = GetAdjustmentRuleForTime(dateTime);
1545 DaylightTime daylightTime = GetDaylightTime(dateTime.Year, rule);
1546 isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime);
1557 // GetIsInvalidTime -
1559 // Helper function that checks if a given DateTime is in an invalid time ("time hole")
1560 // A "time hole" occurs at a DST transition point when time jumps forward;
1561 // For example, in Pacific Standard Time on Sunday, April 2, 2006 time jumps from
1562 // 1:59:59.9999999 to 3AM. The time range 2AM to 2:59:59.9999999AM is the "time hole".
1563 // A "time hole" is not limited to only occurring at the start of DST, and may occur at
1564 // the end of DST as well.
1566 static private Boolean GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTime daylightTime) {
1567 Boolean isInvalid = false;
1568 if (rule == null || rule.DaylightDelta == TimeSpan.Zero) {
1572 DateTime startInvalidTime;
1573 DateTime endInvalidTime;
1575 // if at DST start we transition forward in time then there is an ambiguous time range at the DST end
1576 if (rule.DaylightDelta < TimeSpan.Zero) {
1577 startInvalidTime = daylightTime.End;
1578 endInvalidTime = daylightTime.End - rule.DaylightDelta; /* */
1581 startInvalidTime = daylightTime.Start;
1582 endInvalidTime = daylightTime.Start + rule.DaylightDelta; /* */
1585 isInvalid = (time >= startInvalidTime && time < endInvalidTime);
1587 if (!isInvalid && startInvalidTime.Year != endInvalidTime.Year) {
1588 // there exists an extreme corner case where the start or end period is on a year boundary and
1589 // because of this the comparison above might have been performed for a year-early or a year-later
1590 // than it should have been.
1591 DateTime startModifiedInvalidTime;
1592 DateTime endModifiedInvalidTime;
1594 startModifiedInvalidTime = startInvalidTime.AddYears(1);
1595 endModifiedInvalidTime = endInvalidTime.AddYears(1);
1596 isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
1598 catch (ArgumentOutOfRangeException) {}
1602 startModifiedInvalidTime = startInvalidTime.AddYears(-1);
1603 endModifiedInvalidTime = endInvalidTime.AddYears(-1);
1604 isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
1606 catch (ArgumentOutOfRangeException) {}
1615 public readonly int Offset;
1616 public readonly bool IsDst;
1619 public TimeType (int offset, bool is_dst, string abbrev)
1621 this.Offset = offset;
1622 this.IsDst = is_dst;
1626 public override string ToString ()
1628 return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;