5 * Stephane Delcroix <stephane@delcroix.org>
7 * Copyright 2011 Xamarin Inc.
9 * Permission is hereby granted, free of charge, to any person obtaining
10 * a copy of this software and associated documentation files (the
11 * "Software"), to deal in the Software without restriction, including
12 * without limitation the rights to use, copy, modify, merge, publish,
13 * distribute, sublicense, and/or sell copies of the Software, and to
14 * permit persons to whom the Software is furnished to do so, subject to
15 * the following conditions:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Runtime.CompilerServices;
32 #if !INSIDE_CORLIB && (NET_4_0 || MOONLIGHT || MOBILE)
34 [assembly:TypeForwardedTo (typeof(TimeZoneInfo))]
36 #elif (INSIDE_CORLIB && (NET_4_0 || MOONLIGHT || MOBILE)) || (!INSIDE_CORLIB && (NET_3_5 && !NET_4_0 && !MOBILE))
38 using System.Collections.Generic;
39 using System.Collections.ObjectModel;
40 using System.Runtime.Serialization;
48 using Microsoft.Win32;
53 [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
54 #elif MOONLIGHT || MOBILE
55 [TypeForwardedFrom (Consts.AssemblySystem_Core)]
57 [SerializableAttribute]
58 public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
60 TimeSpan baseUtcOffset;
61 public TimeSpan BaseUtcOffset {
62 get { return baseUtcOffset; }
65 string daylightDisplayName;
66 public string DaylightName {
68 if (disableDaylightSavingTime)
70 return daylightDisplayName;
75 public string DisplayName {
76 get { return displayName; }
84 static TimeZoneInfo local;
85 public static TimeZoneInfo Local {
89 local = ZoneInfoDB.Default;
91 using (Stream stream = GetMonoTouchDefault ()) {
92 return BuildFromStream ("Local", stream);
96 local = FindSystemTimeZoneByFileName ("Local", "/etc/localtime");
99 local = FindSystemTimeZoneByFileName ("Local", Path.Combine (TimeZoneDirectory, "localtime"));
101 throw new TimeZoneNotFoundException ();
105 throw new TimeZoneNotFoundException ();
112 string standardDisplayName;
113 public string StandardName {
114 get { return standardDisplayName; }
117 bool disableDaylightSavingTime;
118 public bool SupportsDaylightSavingTime {
119 get { return !disableDaylightSavingTime; }
122 static TimeZoneInfo utc;
123 public static TimeZoneInfo Utc {
126 utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
131 static string timeZoneDirectory = null;
132 static string TimeZoneDirectory {
134 if (timeZoneDirectory == null)
135 timeZoneDirectory = "/usr/share/zoneinfo";
136 return timeZoneDirectory;
140 timeZoneDirectory = value;
144 private AdjustmentRule [] adjustmentRules;
147 static RegistryKey timeZoneKey = null;
148 static bool timeZoneKeySet = false;
149 static RegistryKey TimeZoneKey {
151 if (!timeZoneKeySet) {
152 int p = (int) Environment.OSVersion.Platform;
153 /* Only use the registry on non-Unix platforms. */
154 if ((p != 4) && (p != 6) && (p != 128))
155 timeZoneKey = Registry.LocalMachine.OpenSubKey (
156 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
158 timeZoneKeySet = true;
165 public static void ClearCachedData ()
169 systemTimeZones = null;
172 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
174 return ConvertTime (dateTime, TimeZoneInfo.Local, destinationTimeZone);
177 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
179 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
180 throw new ArgumentException ("Kind propery of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
182 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
183 throw new ArgumentException ("Kind propery of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
185 if (sourceTimeZone.IsInvalidTime (dateTime))
186 throw new ArgumentException ("dateTime parameter is an invalid time");
188 if (sourceTimeZone == null)
189 throw new ArgumentNullException ("sourceTimeZone");
191 if (destinationTimeZone == null)
192 throw new ArgumentNullException ("destinationTimeZone");
194 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
197 DateTime utc = ConvertTimeToUtc (dateTime);
199 if (destinationTimeZone == TimeZoneInfo.Utc)
202 return ConvertTimeFromUtc (utc, destinationTimeZone);
206 public static DateTimeOffset ConvertTime (DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
208 throw new NotImplementedException ();
211 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
213 return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
216 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
218 return ConvertTime (dateTime, FindSystemTimeZoneById (sourceTimeZoneId), FindSystemTimeZoneById (destinationTimeZoneId));
221 public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
223 return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
226 private DateTime ConvertTimeFromUtc (DateTime dateTime)
228 if (dateTime.Kind == DateTimeKind.Local)
229 throw new ArgumentException ("Kind property of dateTime is Local");
231 if (this == TimeZoneInfo.Utc)
232 return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
234 //FIXME: do not rely on DateTime implementation !
235 if (this == TimeZoneInfo.Local)
236 return DateTime.SpecifyKind (dateTime.ToLocalTime (), DateTimeKind.Unspecified);
238 AdjustmentRule rule = GetApplicableRule (dateTime);
240 if (rule != null && IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
241 return DateTime.SpecifyKind (dateTime + BaseUtcOffset + rule.DaylightDelta , DateTimeKind.Unspecified);
243 return DateTime.SpecifyKind (dateTime + BaseUtcOffset, DateTimeKind.Unspecified);
246 public static DateTime ConvertTimeFromUtc (DateTime dateTime, TimeZoneInfo destinationTimeZone)
248 if (destinationTimeZone == null)
249 throw new ArgumentNullException ("destinationTimeZone");
251 return destinationTimeZone.ConvertTimeFromUtc (dateTime);
254 public static DateTime ConvertTimeToUtc (DateTime dateTime)
256 if (dateTime.Kind == DateTimeKind.Utc)
259 //FIXME: do not rely on DateTime implementation !
260 return DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc);
263 public static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone)
265 if (sourceTimeZone == null)
266 throw new ArgumentNullException ("sourceTimeZone");
268 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
269 throw new ArgumentException ("Kind propery of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
271 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
272 throw new ArgumentException ("Kind propery of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
274 if (sourceTimeZone.IsInvalidTime (dateTime))
275 throw new ArgumentException ("dateTime parameter is an invalid time");
277 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone == TimeZoneInfo.Utc)
280 if (dateTime.Kind == DateTimeKind.Utc)
283 if (dateTime.Kind == DateTimeKind.Local)
284 return ConvertTimeToUtc (dateTime);
286 if (sourceTimeZone.IsAmbiguousTime (dateTime) || !sourceTimeZone.IsDaylightSavingTime (dateTime))
287 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
289 AdjustmentRule rule = sourceTimeZone.GetApplicableRule (dateTime);
291 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
293 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
297 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName)
299 return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
302 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
304 return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
307 public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
309 return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
312 public bool Equals (TimeZoneInfo other)
317 return other.Id == this.Id && HasSameRules (other);
320 public static TimeZoneInfo FindSystemTimeZoneById (string id)
322 //FIXME: this method should check for cached values in systemTimeZones
324 throw new ArgumentNullException ("id");
326 if (TimeZoneKey != null)
328 RegistryKey key = TimeZoneKey.OpenSubKey (id, false);
330 throw new TimeZoneNotFoundException ();
331 return FromRegistryKey(id, key);
335 return ZoneInfoDB.GetTimeZone (id);
337 // Local requires special logic that already exists in the Local property (bug #326)
341 using (Stream stream = GetMonoTouchData (id)) {
342 return BuildFromStream (id, stream);
345 string filepath = Path.Combine (TimeZoneDirectory, id);
346 return FindSystemTimeZoneByFileName (id, filepath);
348 throw new NotImplementedException ();
354 private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
356 if (!File.Exists (filepath))
357 throw new TimeZoneNotFoundException ();
359 using (FileStream stream = File.OpenRead (filepath)) {
360 return BuildFromStream (id, stream);
364 #if LIBC || MONOTOUCH
365 const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
367 private static TimeZoneInfo BuildFromStream (string id, Stream stream)
369 byte [] buffer = new byte [BUFFER_SIZE];
370 int length = stream.Read (buffer, 0, BUFFER_SIZE);
372 if (!ValidTZFile (buffer, length))
373 throw new InvalidTimeZoneException ("TZ file too big for the buffer");
376 return ParseTZBuffer (id, buffer, length);
377 } catch (Exception e) {
378 throw new InvalidTimeZoneException (e.Message);
384 private static TimeZoneInfo FromRegistryKey (string id, RegistryKey key)
386 byte [] reg_tzi = (byte []) key.GetValue ("TZI");
389 throw new InvalidTimeZoneException ();
391 int bias = BitConverter.ToInt32 (reg_tzi, 0);
392 TimeSpan baseUtcOffset = new TimeSpan (0, -bias, 0);
394 string display_name = (string) key.GetValue ("Display");
395 string standard_name = (string) key.GetValue ("Std");
396 string daylight_name = (string) key.GetValue ("Dlt");
398 List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
400 RegistryKey dst_key = key.OpenSubKey ("Dynamic DST", false);
401 if (dst_key != null) {
402 int first_year = (int) dst_key.GetValue ("FirstEntry");
403 int last_year = (int) dst_key.GetValue ("LastEntry");
406 for (year=first_year; year<=last_year; year++) {
407 byte [] dst_tzi = (byte []) dst_key.GetValue (year.ToString ());
408 if (dst_tzi != null) {
409 int start_year = year == first_year ? 1 : year;
410 int end_year = year == last_year ? 9999 : year;
411 ParseRegTzi(adjustmentRules, start_year, end_year, dst_tzi);
416 ParseRegTzi(adjustmentRules, 1, 9999, reg_tzi);
418 return CreateCustomTimeZone (id, baseUtcOffset, display_name, standard_name, daylight_name, ValidateRules (adjustmentRules).ToArray ());
421 private static void ParseRegTzi (List<AdjustmentRule> adjustmentRules, int start_year, int end_year, byte [] buffer)
423 //int standard_bias = BitConverter.ToInt32 (buffer, 4); /* not sure how to handle this */
424 int daylight_bias = BitConverter.ToInt32 (buffer, 8);
426 int standard_year = BitConverter.ToInt16 (buffer, 12);
427 int standard_month = BitConverter.ToInt16 (buffer, 14);
428 int standard_dayofweek = BitConverter.ToInt16 (buffer, 16);
429 int standard_day = BitConverter.ToInt16 (buffer, 18);
430 int standard_hour = BitConverter.ToInt16 (buffer, 20);
431 int standard_minute = BitConverter.ToInt16 (buffer, 22);
432 int standard_second = BitConverter.ToInt16 (buffer, 24);
433 int standard_millisecond = BitConverter.ToInt16 (buffer, 26);
435 int daylight_year = BitConverter.ToInt16 (buffer, 28);
436 int daylight_month = BitConverter.ToInt16 (buffer, 30);
437 int daylight_dayofweek = BitConverter.ToInt16 (buffer, 32);
438 int daylight_day = BitConverter.ToInt16 (buffer, 34);
439 int daylight_hour = BitConverter.ToInt16 (buffer, 36);
440 int daylight_minute = BitConverter.ToInt16 (buffer, 38);
441 int daylight_second = BitConverter.ToInt16 (buffer, 40);
442 int daylight_millisecond = BitConverter.ToInt16 (buffer, 42);
444 if (standard_month == 0 || daylight_month == 0)
448 DateTime start_timeofday = new DateTime (1, 1, 1, daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
449 TransitionTime start_transition_time;
451 if (daylight_year == 0) {
452 start_date = new DateTime (start_year, 1, 1);
453 start_transition_time = TransitionTime.CreateFloatingDateRule (
454 start_timeofday, daylight_month, daylight_day,
455 (DayOfWeek) daylight_dayofweek);
458 start_date = new DateTime (daylight_year, daylight_month, daylight_day,
459 daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
460 start_transition_time = TransitionTime.CreateFixedDateRule (
461 start_timeofday, daylight_month, daylight_day);
465 DateTime end_timeofday = new DateTime (1, 1, 1, standard_hour, standard_minute, standard_second, standard_millisecond);
466 TransitionTime end_transition_time;
468 if (standard_year == 0) {
469 end_date = new DateTime (end_year, 12, 31);
470 end_transition_time = TransitionTime.CreateFloatingDateRule (
471 end_timeofday, standard_month, standard_day,
472 (DayOfWeek) standard_dayofweek);
475 end_date = new DateTime (standard_year, standard_month, standard_day,
476 standard_hour, standard_minute, standard_second, standard_millisecond);
477 end_transition_time = TransitionTime.CreateFixedDateRule (
478 end_timeofday, standard_month, standard_day);
481 TimeSpan daylight_delta = new TimeSpan(0, -daylight_bias, 0);
483 adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (
484 start_date, end_date, daylight_delta,
485 start_transition_time, end_transition_time));
489 public static TimeZoneInfo FromSerializedString (string source)
491 throw new NotImplementedException ();
494 public AdjustmentRule [] GetAdjustmentRules ()
496 if (disableDaylightSavingTime)
497 return new AdjustmentRule [0];
499 return (AdjustmentRule []) adjustmentRules.Clone ();
502 public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
504 if (!IsAmbiguousTime (dateTime))
505 throw new ArgumentException ("dateTime is not an ambiguous time");
507 AdjustmentRule rule = GetApplicableRule (dateTime);
509 return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
511 return new TimeSpan[] {baseUtcOffset, baseUtcOffset};
514 public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
516 if (!IsAmbiguousTime (dateTimeOffset))
517 throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
519 throw new NotImplementedException ();
522 public override int GetHashCode ()
524 int hash_code = Id.GetHashCode ();
525 foreach (AdjustmentRule rule in GetAdjustmentRules ())
526 hash_code ^= rule.GetHashCode ();
531 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
533 public void GetObjectData (SerializationInfo info, StreamingContext context)
536 throw new NotImplementedException ();
539 //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
540 private static List<TimeZoneInfo> systemTimeZones = null;
541 public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
543 if (systemTimeZones == null) {
544 systemTimeZones = new List<TimeZoneInfo> ();
546 if (TimeZoneKey != null) {
547 foreach (string id in TimeZoneKey.GetSubKeyNames ()) {
549 systemTimeZones.Add (FindSystemTimeZoneById (id));
553 return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
557 foreach (string id in ZoneInfoDB.GetAvailableIds ()) {
558 systemTimeZones.Add (ZoneInfoDB.GetTimeZone (id));
561 if (systemTimeZones.Count == 0) {
562 foreach (string name in GetMonoTouchNames ()) {
563 using (Stream stream = GetMonoTouchData (name)) {
564 systemTimeZones.Add (BuildFromStream (name, stream));
569 string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
570 foreach (string continent in continents) {
572 foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
574 string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
575 systemTimeZones.Add (FindSystemTimeZoneById (id));
576 } catch (ArgumentNullException) {
577 } catch (TimeZoneNotFoundException) {
578 } catch (InvalidTimeZoneException) {
579 } catch (Exception) {
586 throw new NotImplementedException ("This method is not implemented for this platform");
589 return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
592 public TimeSpan GetUtcOffset (DateTime dateTime)
594 if (IsDaylightSavingTime (dateTime)) {
595 AdjustmentRule rule = GetApplicableRule (dateTime);
597 return BaseUtcOffset + rule.DaylightDelta;
600 return BaseUtcOffset;
603 public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
605 throw new NotImplementedException ();
608 public bool HasSameRules (TimeZoneInfo other)
611 throw new ArgumentNullException ("other");
613 if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
616 if (this.adjustmentRules == null)
619 if (this.BaseUtcOffset != other.BaseUtcOffset)
622 if (this.adjustmentRules.Length != other.adjustmentRules.Length)
625 for (int i = 0; i < adjustmentRules.Length; i++) {
626 if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
633 public bool IsAmbiguousTime (DateTime dateTime)
635 if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
636 throw new ArgumentException ("Kind is Local and time is Invalid");
638 if (this == TimeZoneInfo.Utc)
641 if (dateTime.Kind == DateTimeKind.Utc)
642 dateTime = ConvertTimeFromUtc (dateTime);
644 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
645 dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
647 AdjustmentRule rule = GetApplicableRule (dateTime);
649 DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
650 if (dateTime > tpoint - rule.DaylightDelta && dateTime <= tpoint)
657 public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
659 throw new NotImplementedException ();
662 public bool IsDaylightSavingTime (DateTime dateTime)
664 if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
665 throw new ArgumentException ("dateTime is invalid and Kind is Local");
667 if (this == TimeZoneInfo.Utc)
670 if (!SupportsDaylightSavingTime)
672 //FIXME: do not rely on DateTime implementation !
673 if ((dateTime.Kind == DateTimeKind.Local || dateTime.Kind == DateTimeKind.Unspecified) && this == TimeZoneInfo.Local)
674 return dateTime.IsDaylightSavingTime ();
676 //FIXME: do not rely on DateTime implementation !
677 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Utc)
678 return IsDaylightSavingTime (DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc));
680 AdjustmentRule rule = GetApplicableRule (dateTime.Date);
684 DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
685 DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
686 if (dateTime.Kind == DateTimeKind.Utc) {
687 DST_start -= BaseUtcOffset;
688 DST_end -= (BaseUtcOffset + rule.DaylightDelta);
691 return (dateTime >= DST_start && dateTime < DST_end);
694 public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
696 throw new NotImplementedException ();
699 public bool IsInvalidTime (DateTime dateTime)
701 if (dateTime.Kind == DateTimeKind.Utc)
703 if (dateTime.Kind == DateTimeKind.Local && this != Local)
706 AdjustmentRule rule = GetApplicableRule (dateTime);
708 DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
709 if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
717 void IDeserializationCallback.OnDeserialization (object sender)
719 public void OnDeserialization (object sender)
722 throw new NotImplementedException ();
725 public string ToSerializedString ()
727 throw new NotImplementedException ();
730 public override string ToString ()
735 private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
738 throw new ArgumentNullException ("id");
740 if (id == String.Empty)
741 throw new ArgumentException ("id parameter is an empty string");
743 if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
744 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
746 if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
747 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
751 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
754 if (adjustmentRules != null && adjustmentRules.Length != 0) {
755 AdjustmentRule prev = null;
756 foreach (AdjustmentRule current in adjustmentRules) {
758 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
760 if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
761 (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
762 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;");
764 if (prev != null && prev.DateStart > current.DateStart)
765 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
767 if (prev != null && prev.DateEnd > current.DateStart)
768 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
770 if (prev != null && prev.DateEnd == current.DateStart)
771 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
778 this.baseUtcOffset = baseUtcOffset;
779 this.displayName = displayName ?? id;
780 this.standardDisplayName = standardDisplayName ?? id;
781 this.daylightDisplayName = daylightDisplayName;
782 this.disableDaylightSavingTime = disableDaylightSavingTime;
783 this.adjustmentRules = adjustmentRules;
786 private AdjustmentRule GetApplicableRule (DateTime dateTime)
788 //Transitions are always in standard time
789 DateTime date = dateTime;
791 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
792 date = date.ToUniversalTime () + BaseUtcOffset;
794 if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
795 date = date + BaseUtcOffset;
797 if (adjustmentRules != null) {
798 foreach (AdjustmentRule rule in adjustmentRules) {
799 if (rule.DateStart > date.Date)
801 if (rule.DateEnd < date.Date)
809 private static DateTime TransitionPoint (TransitionTime transition, int year)
811 if (transition.IsFixedDateRule)
812 return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
814 DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
815 int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first) % 7;
816 if (day > DateTime.DaysInMonth (year, transition.Month))
818 return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
821 static List<AdjustmentRule> ValidateRules (List<AdjustmentRule> adjustmentRules)
823 AdjustmentRule prev = null;
824 foreach (AdjustmentRule current in adjustmentRules.ToArray ()) {
825 if (prev != null && prev.DateEnd > current.DateStart) {
826 adjustmentRules.Remove (current);
830 return adjustmentRules;
833 #if LIBC || MONODROID
834 private static bool ValidTZFile (byte [] buffer, int length)
836 StringBuilder magic = new StringBuilder ();
838 for (int i = 0; i < 4; i++)
839 magic.Append ((char)buffer [i]);
841 if (magic.ToString () != "TZif")
844 if (length >= BUFFER_SIZE)
850 static int SwapInt32 (int i)
852 return (((i >> 24) & 0xff)
853 | ((i >> 8) & 0xff00)
854 | ((i << 8) & 0xff0000)
858 static int ReadBigEndianInt32 (byte [] buffer, int start)
860 int i = BitConverter.ToInt32 (buffer, start);
861 if (!BitConverter.IsLittleEndian)
864 return SwapInt32 (i);
867 private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
869 //Reading the header. 4 bytes for magic, 16 are reserved
870 int ttisgmtcnt = ReadBigEndianInt32 (buffer, 20);
871 int ttisstdcnt = ReadBigEndianInt32 (buffer, 24);
872 int leapcnt = ReadBigEndianInt32 (buffer, 28);
873 int timecnt = ReadBigEndianInt32 (buffer, 32);
874 int typecnt = ReadBigEndianInt32 (buffer, 36);
875 int charcnt = ReadBigEndianInt32 (buffer, 40);
877 if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
878 throw new InvalidTimeZoneException ();
880 Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
881 Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
882 List<KeyValuePair<DateTime, TimeType>> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
884 if (time_types.Count == 0)
885 throw new InvalidTimeZoneException ();
887 if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
888 throw new InvalidTimeZoneException ();
890 TimeSpan baseUtcOffset = new TimeSpan (0);
891 TimeSpan dstDelta = new TimeSpan (0);
892 string standardDisplayName = null;
893 string daylightDisplayName = null;
894 bool dst_observed = false;
895 DateTime dst_start = DateTime.MinValue;
896 List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
898 for (int i = 0; i < transitions.Count; i++) {
899 var pair = transitions [i];
900 DateTime ttime = pair.Key;
901 TimeType ttype = pair.Value;
903 if (standardDisplayName != ttype.Name || baseUtcOffset.TotalSeconds != ttype.Offset) {
904 standardDisplayName = ttype.Name;
905 daylightDisplayName = null;
906 baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
907 adjustmentRules = new List<AdjustmentRule> ();
908 dst_observed = false;
911 //FIXME: check additional fields for this:
912 //most of the transitions are expressed in GMT
913 dst_start += baseUtcOffset;
914 DateTime dst_end = ttime + baseUtcOffset + dstDelta;
916 //some weird timezone (America/Phoenix) have end dates on Jan 1st
917 if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
918 dst_end -= new TimeSpan (24, 0, 0);
920 DateTime dateStart, dateEnd;
921 if (dst_start.Month < 7)
922 dateStart = new DateTime (dst_start.Year, 1, 1);
924 dateStart = new DateTime (dst_start.Year, 7, 1);
926 if (dst_end.Month >= 7)
927 dateEnd = new DateTime (dst_end.Year, 12, 31);
929 dateEnd = new DateTime (dst_end.Year, 6, 30);
932 TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
933 TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
934 if (transition_start != transition_end) //y, that happened in Argentina in 1943-1946
935 adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
937 dst_observed = false;
939 if (daylightDisplayName != ttype.Name || dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds) {
940 daylightDisplayName = ttype.Name;
941 dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
948 if (adjustmentRules.Count == 0) {
949 TimeType t = (TimeType)time_types [0];
950 if (standardDisplayName == null) {
951 standardDisplayName = t.Name;
952 baseUtcOffset = new TimeSpan (0, 0, t.Offset);
954 return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
956 return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, ValidateRules (adjustmentRules).ToArray ());
960 static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
962 var abbrevs = new Dictionary<int, string> ();
963 int abbrev_index = 0;
964 var sb = new StringBuilder ();
965 for (int i = 0; i < count; i++) {
966 char c = (char) buffer [index + i];
970 abbrevs.Add (abbrev_index, sb.ToString ());
971 //Adding all the substrings too, as it seems to be used, at least for Africa/Windhoek
972 for (int j = 1; j < sb.Length; j++)
973 abbrevs.Add (abbrev_index + j, sb.ToString (j, sb.Length - j));
974 abbrev_index = i + 1;
975 sb = new StringBuilder ();
981 static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
983 var types = new Dictionary<int, TimeType> (count);
984 for (int i = 0; i < count; i++) {
985 int offset = ReadBigEndianInt32 (buffer, index + 6 * i);
986 byte is_dst = buffer [index + 6 * i + 4];
987 byte abbrev = buffer [index + 6 * i + 5];
988 types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
993 static List<KeyValuePair<DateTime, TimeType>> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
995 var list = new List<KeyValuePair<DateTime, TimeType>> (count);
996 for (int i = 0; i < count; i++) {
997 int unixtime = ReadBigEndianInt32 (buffer, index + 4 * i);
998 DateTime ttime = DateTimeFromUnixTime (unixtime);
999 byte ttype = buffer [index + 4 * count + i];
1000 list.Add (new KeyValuePair<DateTime, TimeType> (ttime, time_types [(int)ttype]));
1005 static DateTime DateTimeFromUnixTime (long unix_time)
1007 DateTime date_time = new DateTime (1970, 1, 1);
1008 return date_time.AddSeconds (unix_time);
1013 public readonly int Offset;
1014 public readonly bool IsDst;
1017 public TimeType (int offset, bool is_dst, string abbrev)
1019 this.Offset = offset;
1020 this.IsDst = is_dst;
1024 public override string ToString ()
1026 return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;