Revert "Revert "Merge branch 'master' of https://github.com/mono/mono""
[mono.git] / mcs / class / System.Core / System / TimeZoneInfo.cs
1
2 /*
3  * System.TimeZoneInfo
4  *
5  * Author(s)
6  *      Stephane Delcroix <stephane@delcroix.org>
7  *
8  * Copyright 2011 Xamarin Inc.
9  *
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:
17  * 
18  * The above copyright notice and this permission notice shall be
19  * included in all copies or substantial portions of the Software.
20  * 
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.
28  */
29
30 using System;
31 using System.Runtime.CompilerServices;
32 using System.Threading;
33
34 #if !INSIDE_CORLIB && NET_4_0
35
36 [assembly:TypeForwardedTo (typeof(TimeZoneInfo))]
37
38 #elif (INSIDE_CORLIB && NET_4_0) || (!INSIDE_CORLIB && (NET_3_5 && !NET_4_0 && !MOBILE))
39
40 using System.Collections.Generic;
41 using System.Collections.ObjectModel;
42 using System.Runtime.Serialization;
43 using System.Text;
44
45 #if LIBC || MONODROID
46 using System.IO;
47 using Mono;
48 #endif
49
50 using Microsoft.Win32;
51
52 namespace System
53 {
54 #if MOBILE
55         [TypeForwardedFrom (Consts.AssemblySystem_Core)]
56 #elif NET_4_0
57         [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
58 #endif
59         [SerializableAttribute]
60         public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
61         {
62                 TimeSpan baseUtcOffset;
63                 public TimeSpan BaseUtcOffset {
64                         get { return baseUtcOffset; }
65                 }
66
67                 string daylightDisplayName;
68                 public string DaylightName {
69                         get { 
70                                 return supportsDaylightSavingTime
71                                         ? daylightDisplayName
72                                         : string.Empty;
73                         }
74                 }
75
76                 string displayName;
77                 public string DisplayName {
78                         get { return displayName; }
79                 }
80
81                 string id;
82                 public string Id {
83                         get { return id; }
84                 }
85
86                 static TimeZoneInfo local;
87                 public static TimeZoneInfo Local {
88                         get { 
89                                 var l = local;
90                                 if (l == null) {
91                                         l = CreateLocal ();
92                                         if (l == null)
93                                                 throw new TimeZoneNotFoundException ();
94
95                                         if (Interlocked.CompareExchange (ref local, l, null) != null)
96                                                 l = local;
97                                 }
98
99                                 return l;
100                         }
101                 }
102
103                 static TimeZoneInfo CreateLocal ()
104                 {
105 #if MONODROID
106                         return AndroidTimeZones.Default;
107 #elif MONOTOUCH
108                         using (Stream stream = GetMonoTouchData (null)) {
109                                 return BuildFromStream ("Local", stream);
110                         }
111 #elif LIBC
112                         try {
113                                 return FindSystemTimeZoneByFileName ("Local", "/etc/localtime");        
114                         } catch {
115                                 try {
116                                         return FindSystemTimeZoneByFileName ("Local", Path.Combine (TimeZoneDirectory, "localtime"));   
117                                 } catch {
118                                         return null;
119                                 }
120                         }
121 #else
122                         if (IsWindows && LocalZoneKey != null) {
123                                 string name = (string)LocalZoneKey.GetValue ("TimeZoneKeyName");
124                                 name = TrimSpecial (name);
125                                 if (name != null)
126                                         return TimeZoneInfo.FindSystemTimeZoneById (name);
127                         }
128
129                         return null;
130 #endif
131                 }
132
133                 string standardDisplayName;
134                 public string StandardName {
135                         get { return standardDisplayName; }
136                 }
137
138                 bool supportsDaylightSavingTime;
139                 public bool SupportsDaylightSavingTime {
140                         get  { return supportsDaylightSavingTime; }
141                 }
142
143                 static TimeZoneInfo utc;
144                 public static TimeZoneInfo Utc {
145                         get {
146                                 if (utc == null)
147                                         utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
148                                 return utc;
149                         }
150                 }
151 #if LIBC
152                 static string timeZoneDirectory;
153                 static string TimeZoneDirectory {
154                         get {
155                                 if (timeZoneDirectory == null)
156                                         timeZoneDirectory = "/usr/share/zoneinfo";
157                                 return timeZoneDirectory;
158                         }
159                         set {
160                                 ClearCachedData ();
161                                 timeZoneDirectory = value;
162                         }
163                 }
164 #endif
165                 private AdjustmentRule [] adjustmentRules;
166
167 #if !NET_2_1
168                 /// <summary>
169                 /// Determine whether windows of not (taken Stephane Delcroix's code)
170                 /// </summary>
171                 private static bool IsWindows
172                 {
173                         get {
174                                 int platform = (int) Environment.OSVersion.Platform;
175                                 return ((platform != 4) && (platform != 6) && (platform != 128));
176                         }
177                 }
178                 
179                 /// <summary>
180                 /// Needed to trim misc garbage in MS registry keys
181                 /// </summary>
182                 private static string TrimSpecial (string str)
183                 {
184                         var Istart = 0;
185                         while (Istart < str.Length && !char.IsLetterOrDigit(str[Istart])) Istart++;
186                         var Iend = str.Length - 1;
187                         while (Iend > Istart && !char.IsLetterOrDigit(str[Iend])) Iend--;
188                         
189                         return str.Substring (Istart, Iend-Istart+1);
190                 }
191                 
192                 static RegistryKey timeZoneKey;
193                 static RegistryKey TimeZoneKey {
194                         get {
195                                 if (timeZoneKey != null)
196                                         return timeZoneKey;
197                                 if (!IsWindows)
198                                         return null;
199                                 
200                                 return timeZoneKey = Registry.LocalMachine.OpenSubKey (
201                                         "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
202                                         false);
203                         }
204                 }
205                 
206                 static RegistryKey localZoneKey;
207                 static RegistryKey LocalZoneKey {
208                         get {
209                                 if (localZoneKey != null)
210                                         return localZoneKey;
211                                 
212                                 if (!IsWindows)
213                                         return null;
214                                 
215                                 return localZoneKey = Registry.LocalMachine.OpenSubKey (
216                                         "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation", false);
217                         }
218                 }
219 #endif
220
221                 public static void ClearCachedData ()
222                 {
223                         local = null;
224                         utc = null;
225                         systemTimeZones = null;
226                 }
227
228                 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
229                 {
230                         return ConvertTime (dateTime, dateTime.Kind == DateTimeKind.Utc ? TimeZoneInfo.Utc : TimeZoneInfo.Local, destinationTimeZone);
231                 }
232
233                 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
234                 {
235                         if (sourceTimeZone == null)
236                                 throw new ArgumentNullException ("sourceTimeZone");
237
238                         if (destinationTimeZone == null)
239                                 throw new ArgumentNullException ("destinationTimeZone");
240                         
241                         if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
242                                 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
243
244                         if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
245                                 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
246                         
247                         if (sourceTimeZone.IsInvalidTime (dateTime))
248                                 throw new ArgumentException ("dateTime parameter is an invalid time");
249
250                         if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
251                                 return dateTime;
252
253                         DateTime utc = ConvertTimeToUtc (dateTime);
254
255                         if (destinationTimeZone != TimeZoneInfo.Utc) {
256                                 utc = ConvertTimeFromUtc (utc, destinationTimeZone);
257                                 if (dateTime.Kind == DateTimeKind.Unspecified)
258                                         return DateTime.SpecifyKind (utc, DateTimeKind.Unspecified);
259                         }
260                         
261                         return utc;
262                 }
263
264                 public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) 
265                 {
266                         if (destinationTimeZone == null) 
267                                 throw new ArgumentNullException("destinationTimeZone");
268                 
269                         var utcDateTime = dateTimeOffset.UtcDateTime;
270                         AdjustmentRule rule = destinationTimeZone.GetApplicableRule (utcDateTime);
271                 
272                         if (rule != null && destinationTimeZone.IsDaylightSavingTime(utcDateTime)) {
273                                 var offset = destinationTimeZone.BaseUtcOffset + rule.DaylightDelta;
274                                 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + offset, offset);
275                         }
276                         else {
277                                 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + destinationTimeZone.BaseUtcOffset, destinationTimeZone.BaseUtcOffset);
278                         }
279                 }
280
281                 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
282                 {
283                         return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
284                 }
285
286                 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
287                 {
288                         return ConvertTime (dateTime, FindSystemTimeZoneById (sourceTimeZoneId), FindSystemTimeZoneById (destinationTimeZoneId));
289                 }
290
291                 public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
292                 {
293                         return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
294                 }
295
296                 private DateTime ConvertTimeFromUtc (DateTime dateTime)
297                 {
298                         if (dateTime.Kind == DateTimeKind.Local)
299                                 throw new ArgumentException ("Kind property of dateTime is Local");
300
301                         if (this == TimeZoneInfo.Utc)
302                                 return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
303                         
304                         //FIXME: do not rely on DateTime implementation !
305                         if (this == TimeZoneInfo.Local) 
306                         {
307 #if NET_4_0
308                                 return dateTime.ToLocalTime ();
309 #else
310                                 return DateTime.SpecifyKind (dateTime.ToLocalTime (), DateTimeKind.Unspecified);
311 #endif
312                         }
313
314
315                         AdjustmentRule rule = GetApplicableRule (dateTime);
316                         if (rule != null && IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
317                                 return DateTime.SpecifyKind (dateTime + BaseUtcOffset + rule.DaylightDelta , DateTimeKind.Unspecified);
318                         else
319                                 return DateTime.SpecifyKind (dateTime + BaseUtcOffset, DateTimeKind.Unspecified);
320                 }
321
322                 public static DateTime ConvertTimeFromUtc (DateTime dateTime, TimeZoneInfo destinationTimeZone)
323                 {
324                         if (destinationTimeZone == null)
325                                 throw new ArgumentNullException ("destinationTimeZone");
326
327                         return destinationTimeZone.ConvertTimeFromUtc (dateTime);
328                 }
329
330                 public static DateTime ConvertTimeToUtc (DateTime dateTime)
331                 {
332                         if (dateTime.Kind == DateTimeKind.Utc)
333                                 return dateTime;
334
335                         //FIXME: do not rely on DateTime implementation !
336                         return DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc);
337                 }
338
339                 public static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone)
340                 {
341                         if (sourceTimeZone == null)
342                                 throw new ArgumentNullException ("sourceTimeZone");
343
344                         if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
345                                 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
346
347                         if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
348                                 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
349
350                         if (sourceTimeZone.IsInvalidTime (dateTime))
351                                 throw new ArgumentException ("dateTime parameter is an invalid time");
352
353                         if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone == TimeZoneInfo.Utc)
354                                 return dateTime;
355
356                         if (dateTime.Kind == DateTimeKind.Utc)
357                                 return dateTime;
358
359                         if (dateTime.Kind == DateTimeKind.Local)
360                                 return ConvertTimeToUtc (dateTime);
361
362                         if (sourceTimeZone.IsAmbiguousTime (dateTime) || !sourceTimeZone.IsDaylightSavingTime (dateTime))
363                                 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
364                         else {
365                                 AdjustmentRule rule = sourceTimeZone.GetApplicableRule (dateTime);
366                                 if (rule != null)
367                                         return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
368                                 else
369                                         return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
370                         }
371                 }
372
373                 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName) 
374                 {
375                         return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
376                 }
377
378                 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
379                 {
380                         return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
381                 }
382
383                 public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
384                 {
385                         return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
386                 }
387
388 #if NET_4_5
389                 public override bool Equals (object obj)
390                 {
391                         return Equals (obj as TimeZoneInfo);
392                 }
393 #endif
394
395                 public bool Equals (TimeZoneInfo other)
396                 {
397                         if (other == null)
398                                 return false;
399
400                         return other.Id == this.Id && HasSameRules (other);
401                 }
402
403                 public static TimeZoneInfo FindSystemTimeZoneById (string id)
404                 {
405                         //FIXME: this method should check for cached values in systemTimeZones
406                         if (id == null)
407                                 throw new ArgumentNullException ("id");
408 #if !NET_2_1
409                         if (TimeZoneKey != null)
410                         {
411                                 RegistryKey key = TimeZoneKey.OpenSubKey (id, false);
412                                 if (key == null)
413                                         throw new TimeZoneNotFoundException ();
414                                 return FromRegistryKey(id, key);
415                         }
416 #endif
417 #if MONODROID
418                         var timeZoneInfo = AndroidTimeZones.GetTimeZone (id);
419                         if (timeZoneInfo == null)
420                                 throw new TimeZoneNotFoundException ();
421                         return timeZoneInfo;
422 #else
423                         // Local requires special logic that already exists in the Local property (bug #326)
424                         if (id == "Local")
425                                 return Local;
426 #if MONOTOUCH
427                         using (Stream stream = GetMonoTouchData (id)) {
428                                 return BuildFromStream (id, stream);
429                         }
430 #elif LIBC
431                         string filepath = Path.Combine (TimeZoneDirectory, id);
432                         return FindSystemTimeZoneByFileName (id, filepath);
433 #else
434                         throw new NotImplementedException ();
435 #endif
436 #endif
437                 }
438
439 #if LIBC
440                 private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
441                 {
442                         if (!File.Exists (filepath))
443                                 throw new TimeZoneNotFoundException ();
444
445                         using (FileStream stream = File.OpenRead (filepath)) {
446                                 return BuildFromStream (id, stream);
447                         }
448                 }
449 #endif
450 #if LIBC || MONOTOUCH
451                 const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
452                 
453                 private static TimeZoneInfo BuildFromStream (string id, Stream stream) 
454                 {
455                         byte [] buffer = new byte [BUFFER_SIZE];
456                         int length = stream.Read (buffer, 0, BUFFER_SIZE);
457                         
458                         if (!ValidTZFile (buffer, length))
459                                 throw new InvalidTimeZoneException ("TZ file too big for the buffer");
460
461                         try {
462                                 return ParseTZBuffer (id, buffer, length);
463                         } catch (Exception e) {
464                                 throw new InvalidTimeZoneException (e.Message);
465                         }
466                 }
467 #endif
468
469 #if !NET_2_1
470                 private static TimeZoneInfo FromRegistryKey (string id, RegistryKey key)
471                 {
472                         byte [] reg_tzi = (byte []) key.GetValue ("TZI");
473
474                         if (reg_tzi == null)
475                                 throw new InvalidTimeZoneException ();
476
477                         int bias = BitConverter.ToInt32 (reg_tzi, 0);
478                         TimeSpan baseUtcOffset = new TimeSpan (0, -bias, 0);
479
480                         string display_name = (string) key.GetValue ("Display");
481                         string standard_name = (string) key.GetValue ("Std");
482                         string daylight_name = (string) key.GetValue ("Dlt");
483
484                         List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
485
486                         RegistryKey dst_key = key.OpenSubKey ("Dynamic DST", false);
487                         if (dst_key != null) {
488                                 int first_year = (int) dst_key.GetValue ("FirstEntry");
489                                 int last_year = (int) dst_key.GetValue ("LastEntry");
490                                 int year;
491
492                                 for (year=first_year; year<=last_year; year++) {
493                                         byte [] dst_tzi = (byte []) dst_key.GetValue (year.ToString ());
494                                         if (dst_tzi != null) {
495                                                 int start_year = year == first_year ? 1 : year;
496                                                 int end_year = year == last_year ? 9999 : year;
497                                                 ParseRegTzi(adjustmentRules, start_year, end_year, dst_tzi);
498                                         }
499                                 }
500                         }
501                         else
502                                 ParseRegTzi(adjustmentRules, 1, 9999, reg_tzi);
503
504                         return CreateCustomTimeZone (id, baseUtcOffset, display_name, standard_name, daylight_name, ValidateRules (adjustmentRules).ToArray ());
505                 }
506
507                 private static void ParseRegTzi (List<AdjustmentRule> adjustmentRules, int start_year, int end_year, byte [] buffer)
508                 {
509                         //int standard_bias = BitConverter.ToInt32 (buffer, 4); /* not sure how to handle this */
510                         int daylight_bias = BitConverter.ToInt32 (buffer, 8);
511
512                         int standard_year = BitConverter.ToInt16 (buffer, 12);
513                         int standard_month = BitConverter.ToInt16 (buffer, 14);
514                         int standard_dayofweek = BitConverter.ToInt16 (buffer, 16);
515                         int standard_day = BitConverter.ToInt16 (buffer, 18);
516                         int standard_hour = BitConverter.ToInt16 (buffer, 20);
517                         int standard_minute = BitConverter.ToInt16 (buffer, 22);
518                         int standard_second = BitConverter.ToInt16 (buffer, 24);
519                         int standard_millisecond = BitConverter.ToInt16 (buffer, 26);
520
521                         int daylight_year = BitConverter.ToInt16 (buffer, 28);
522                         int daylight_month = BitConverter.ToInt16 (buffer, 30);
523                         int daylight_dayofweek = BitConverter.ToInt16 (buffer, 32);
524                         int daylight_day = BitConverter.ToInt16 (buffer, 34);
525                         int daylight_hour = BitConverter.ToInt16 (buffer, 36);
526                         int daylight_minute = BitConverter.ToInt16 (buffer, 38);
527                         int daylight_second = BitConverter.ToInt16 (buffer, 40);
528                         int daylight_millisecond = BitConverter.ToInt16 (buffer, 42);
529
530                         if (standard_month == 0 || daylight_month == 0)
531                                 return;
532
533                         DateTime start_date;
534                         DateTime start_timeofday = new DateTime (1, 1, 1, daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
535                         TransitionTime start_transition_time;
536
537                         if (daylight_year == 0) {
538                                 start_date = new DateTime (start_year, 1, 1);
539                                 start_transition_time = TransitionTime.CreateFloatingDateRule (
540                                         start_timeofday, daylight_month, daylight_day,
541                                         (DayOfWeek) daylight_dayofweek);
542                         }
543                         else {
544                                 start_date = new DateTime (daylight_year, daylight_month, daylight_day,
545                                         daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
546                                 start_transition_time = TransitionTime.CreateFixedDateRule (
547                                         start_timeofday, daylight_month, daylight_day);
548                         }
549
550                         DateTime end_date;
551                         DateTime end_timeofday = new DateTime (1, 1, 1, standard_hour, standard_minute, standard_second, standard_millisecond);
552                         TransitionTime end_transition_time;
553
554                         if (standard_year == 0) {
555                                 end_date = new DateTime (end_year, 12, 31);
556                                 end_transition_time = TransitionTime.CreateFloatingDateRule (
557                                         end_timeofday, standard_month, standard_day,
558                                         (DayOfWeek) standard_dayofweek);
559                         }
560                         else {
561                                 end_date = new DateTime (standard_year, standard_month, standard_day,
562                                         standard_hour, standard_minute, standard_second, standard_millisecond);
563                                 end_transition_time = TransitionTime.CreateFixedDateRule (
564                                         end_timeofday, standard_month, standard_day);
565                         }
566
567                         TimeSpan daylight_delta = new TimeSpan(0, -daylight_bias, 0);
568
569                         adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (
570                                 start_date, end_date, daylight_delta,
571                                 start_transition_time, end_transition_time));
572                 }
573 #endif
574
575                 public static TimeZoneInfo FromSerializedString (string source)
576                 {
577                         throw new NotImplementedException ();
578                 }
579
580                 public AdjustmentRule [] GetAdjustmentRules ()
581                 {
582                         if (!supportsDaylightSavingTime)
583                                 return new AdjustmentRule [0];
584                         else
585                                 return (AdjustmentRule []) adjustmentRules.Clone ();
586                 }
587
588                 public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
589                 {
590                         if (!IsAmbiguousTime (dateTime))
591                                 throw new ArgumentException ("dateTime is not an ambiguous time");
592
593                         AdjustmentRule rule = GetApplicableRule (dateTime);
594                         if (rule != null)
595                                 return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
596                         else
597                                 return new TimeSpan[] {baseUtcOffset, baseUtcOffset};
598                 }
599
600                 public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
601                 {
602                         if (!IsAmbiguousTime (dateTimeOffset))
603                                 throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
604
605                         throw new NotImplementedException ();
606                 }
607
608                 public override int GetHashCode ()
609                 {
610                         int hash_code = Id.GetHashCode ();
611                         foreach (AdjustmentRule rule in GetAdjustmentRules ())
612                                 hash_code ^= rule.GetHashCode ();
613                         return hash_code;
614                 }
615
616 #if NET_4_0
617                 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
618 #else
619                 public void GetObjectData (SerializationInfo info, StreamingContext context)
620 #endif
621                 {
622                         if (info == null)
623                                 throw new ArgumentNullException ("info");
624                         info.AddValue ("Id", id);
625                         info.AddValue ("DisplayName", displayName);
626                         info.AddValue ("StandardName", standardDisplayName);
627                         info.AddValue ("DaylightName", daylightDisplayName);
628                         info.AddValue ("BaseUtcOffset", baseUtcOffset);
629                         info.AddValue ("AdjustmentRules", adjustmentRules);
630                         info.AddValue ("SupportsDaylightSavingTime", SupportsDaylightSavingTime);
631                 }
632
633                 //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
634                 private static List<TimeZoneInfo> systemTimeZones;
635                 public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
636                 {
637                         if (systemTimeZones == null) {
638                                 systemTimeZones = new List<TimeZoneInfo> ();
639 #if !NET_2_1
640                                 if (TimeZoneKey != null) {
641                                         foreach (string id in TimeZoneKey.GetSubKeyNames ()) {
642                                                 try {
643                                                         systemTimeZones.Add (FindSystemTimeZoneById (id));
644                                                 } catch {}
645                                         }
646
647                                         return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
648                                 }
649 #endif
650 #if MONODROID
651                         foreach (string id in AndroidTimeZones.GetAvailableIds ()) {
652                                 var tz = AndroidTimeZones.GetTimeZone (id);
653                                 if (tz != null)
654                                         systemTimeZones.Add (tz);
655                         }
656 #elif MONOTOUCH
657                                 if (systemTimeZones.Count == 0) {
658                                         foreach (string name in GetMonoTouchNames ()) {
659                                                 using (Stream stream = GetMonoTouchData (name)) {
660                                                         systemTimeZones.Add (BuildFromStream (name, stream));
661                                                 }
662                                         }
663                                 }
664 #elif LIBC
665                                 string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
666                                 foreach (string continent in continents) {
667                                         try {
668                                                 foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
669                                                         try {
670                                                                 string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
671                                                                 systemTimeZones.Add (FindSystemTimeZoneById (id));
672                                                         } catch (ArgumentNullException) {
673                                                         } catch (TimeZoneNotFoundException) {
674                                                         } catch (InvalidTimeZoneException) {
675                                                         } catch (Exception) {
676                                                                 throw;
677                                                         }
678                                                 }
679                                         } catch {}
680                                 }
681 #else
682                                 throw new NotImplementedException ("This method is not implemented for this platform");
683 #endif
684                         }
685                         return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
686                 }
687
688                 public TimeSpan GetUtcOffset (DateTime dateTime)
689                 {
690                         if (IsDaylightSavingTime (dateTime)) {
691                                 AdjustmentRule rule = GetApplicableRule (dateTime);
692                                 if (rule != null)
693                                         return BaseUtcOffset + rule.DaylightDelta;
694                         }
695                         
696                         return BaseUtcOffset;
697                 }
698
699                 public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
700                 {
701                         throw new NotImplementedException ();
702                 }
703
704                 public bool HasSameRules (TimeZoneInfo other)
705                 {
706                         if (other == null)
707                                 throw new ArgumentNullException ("other");
708
709                         if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
710                                 return false;
711
712                         if (this.adjustmentRules == null)
713                                 return true;
714
715                         if (this.BaseUtcOffset != other.BaseUtcOffset)
716                                 return false;
717
718                         if (this.adjustmentRules.Length != other.adjustmentRules.Length)
719                                 return false;
720
721                         for (int i = 0; i < adjustmentRules.Length; i++) {
722                                 if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
723                                         return false;
724                         }
725                         
726                         return true;
727                 }
728
729                 public bool IsAmbiguousTime (DateTime dateTime)
730                 {
731                         if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
732                                 throw new ArgumentException ("Kind is Local and time is Invalid");
733
734                         if (this == TimeZoneInfo.Utc)
735                                 return false;
736                         
737                         if (dateTime.Kind == DateTimeKind.Utc)
738                                 dateTime = ConvertTimeFromUtc (dateTime);
739
740                         if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
741                                 dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
742
743                         AdjustmentRule rule = GetApplicableRule (dateTime);
744                         if (rule != null) {
745                                 DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
746                                 if (dateTime > tpoint - rule.DaylightDelta  && dateTime <= tpoint)
747                                         return true;
748                         }
749                                 
750                         return false;
751                 }
752
753                 public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
754                 {
755                         throw new NotImplementedException ();
756                 }
757
758                 bool IsInDSTForYear (AdjustmentRule rule, DateTime dateTime, int year)
759                 {
760                         DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, year);
761                         DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
762                         if (dateTime.Kind == DateTimeKind.Utc) {
763                                 DST_start -= BaseUtcOffset;
764                                 DST_end -= (BaseUtcOffset + rule.DaylightDelta);
765                         }
766
767                         return (dateTime >= DST_start && dateTime < DST_end);
768                 }
769                 
770                 public bool IsDaylightSavingTime (DateTime dateTime)
771                 {
772                         if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
773                                 throw new ArgumentException ("dateTime is invalid and Kind is Local");
774
775                         if (this == TimeZoneInfo.Utc)
776                                 return false;
777                         
778                         if (!SupportsDaylightSavingTime)
779                                 return false;
780                         
781                         //FIXME: do not rely on DateTime implementation !
782                         if ((dateTime.Kind == DateTimeKind.Local || dateTime.Kind == DateTimeKind.Unspecified) && this == TimeZoneInfo.Local)
783                                 return dateTime.IsDaylightSavingTime ();
784                         
785                         //FIXME: do not rely on DateTime implementation !
786                         if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Utc)
787                                 return IsDaylightSavingTime (DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc));
788                         
789                         AdjustmentRule rule = GetApplicableRule (dateTime.Date);
790                         if (rule == null)
791                                 return false;
792
793                         // Check whether we're in the dateTime year's DST period
794                         if (IsInDSTForYear (rule, dateTime, dateTime.Year))
795                                 return true;
796
797                         // We might be in the dateTime previous year's DST period
798                         return IsInDSTForYear (rule, dateTime, dateTime.Year - 1);
799                 }
800
801                 public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
802                 {
803                         throw new NotImplementedException ();
804                 }
805
806                 public bool IsInvalidTime (DateTime dateTime)
807                 {
808                         if (dateTime.Kind == DateTimeKind.Utc)
809                                 return false;
810                         if (dateTime.Kind == DateTimeKind.Local && this != Local)
811                                 return false;
812
813                         AdjustmentRule rule = GetApplicableRule (dateTime);
814                         if (rule != null) {
815                                 DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
816                                 if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
817                                         return true;
818                         }
819                                 
820                         return false;
821                 }
822
823 #if NET_4_0
824                 void IDeserializationCallback.OnDeserialization (object sender)
825 #else
826                 public void OnDeserialization (object sender)
827 #endif
828                 {
829                         try {
830                                         TimeZoneInfo.Validate (id, baseUtcOffset, adjustmentRules);
831                                 } catch (ArgumentException ex) {
832                                         throw new SerializationException ("invalid serialization data", ex);
833                                 }
834                 }
835
836                 private static void Validate (string id, TimeSpan baseUtcOffset, AdjustmentRule [] adjustmentRules)
837                 {
838                         if (id == null)
839                                 throw new ArgumentNullException ("id");
840
841                         if (id == String.Empty)
842                                 throw new ArgumentException ("id parameter is an empty string");
843
844                         if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
845                                 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
846
847                         if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
848                                 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
849
850 #if STRICT
851                         if (id.Length > 32)
852                                 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
853 #endif
854
855                         if (adjustmentRules != null && adjustmentRules.Length != 0) {
856                                 AdjustmentRule prev = null;
857                                 foreach (AdjustmentRule current in adjustmentRules) {
858                                         if (current == null)
859                                                 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
860
861                                         if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
862                                                         (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
863                                                 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;");
864
865                                         if (prev != null && prev.DateStart > current.DateStart)
866                                                 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
867                                         
868                                         if (prev != null && prev.DateEnd > current.DateStart)
869                                                 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
870
871                                         if (prev != null && prev.DateEnd == current.DateStart)
872                                                 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
873
874                                         prev = current;
875                                 }
876                         }
877                 }
878                 
879                 public string ToSerializedString ()
880                 {
881                         throw new NotImplementedException ();
882                 }
883
884                 public override string ToString ()
885                 {
886                         return DisplayName;
887                 }
888
889                 private TimeZoneInfo (SerializationInfo info, StreamingContext context)
890                 {
891                         if (info == null)
892                                 throw new ArgumentNullException ("info");
893                         id = (string) info.GetValue ("Id", typeof (string));
894                         displayName = (string) info.GetValue ("DisplayName", typeof (string));
895                         standardDisplayName = (string) info.GetValue ("StandardName", typeof (string));
896                         daylightDisplayName = (string) info.GetValue ("DaylightName", typeof (string));
897                         baseUtcOffset = (TimeSpan) info.GetValue ("BaseUtcOffset", typeof (TimeSpan));
898                         adjustmentRules = (TimeZoneInfo.AdjustmentRule []) info.GetValue ("AdjustmentRules", typeof (TimeZoneInfo.AdjustmentRule []));
899                         supportsDaylightSavingTime = (bool) info.GetValue ("SupportsDaylightSavingTime", typeof (bool));
900                 }
901
902                 private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
903                 {
904                         if (id == null)
905                                 throw new ArgumentNullException ("id");
906
907                         if (id == String.Empty)
908                                 throw new ArgumentException ("id parameter is an empty string");
909
910                         if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
911                                 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
912
913                         if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
914                                 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
915
916 #if STRICT
917                         if (id.Length > 32)
918                                 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
919 #endif
920
921                         bool supportsDaylightSavingTime = !disableDaylightSavingTime;
922
923                         if (adjustmentRules != null && adjustmentRules.Length != 0) {
924                                 AdjustmentRule prev = null;
925                                 foreach (AdjustmentRule current in adjustmentRules) {
926                                         if (current == null)
927                                                 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
928
929                                         if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
930                                                         (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
931                                                 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;");
932
933                                         if (prev != null && prev.DateStart > current.DateStart)
934                                                 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
935                                         
936                                         if (prev != null && prev.DateEnd > current.DateStart)
937                                                 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
938
939                                         if (prev != null && prev.DateEnd == current.DateStart)
940                                                 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
941
942                                         prev = current;
943                                 }
944                         } else {
945                                 supportsDaylightSavingTime = false;
946                         }
947                         
948                         this.id = id;
949                         this.baseUtcOffset = baseUtcOffset;
950                         this.displayName = displayName ?? id;
951                         this.standardDisplayName = standardDisplayName ?? id;
952                         this.daylightDisplayName = daylightDisplayName;
953                         this.supportsDaylightSavingTime = supportsDaylightSavingTime;
954                         this.adjustmentRules = adjustmentRules;
955                 }
956
957                 private AdjustmentRule GetApplicableRule (DateTime dateTime)
958                 {
959                         //Transitions are always in standard time
960                         DateTime date = dateTime;
961
962                         if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
963                                 date = date.ToUniversalTime () + BaseUtcOffset;
964
965                         if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
966                                 date = date + BaseUtcOffset;
967
968                         if (adjustmentRules != null) {
969                                 foreach (AdjustmentRule rule in adjustmentRules) {
970                                         if (rule.DateStart > date.Date)
971                                                 return null;
972                                         if (rule.DateEnd < date.Date)
973                                                 continue;
974                                         return rule;
975                                 }
976                         }
977                         return null;
978                 }
979
980                 private static DateTime TransitionPoint (TransitionTime transition, int year)
981                 {
982                         if (transition.IsFixedDateRule)
983                                 return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
984
985                         DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
986                         int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first) % 7;
987                         if (day >  DateTime.DaysInMonth (year, transition.Month))
988                                 day -= 7;
989                         return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
990                 }
991
992                 static List<AdjustmentRule> ValidateRules (List<AdjustmentRule> adjustmentRules)
993                 {
994                         AdjustmentRule prev = null;
995                         foreach (AdjustmentRule current in adjustmentRules.ToArray ()) {
996                                 if (prev != null && prev.DateEnd > current.DateStart) {
997                                         adjustmentRules.Remove (current);
998                                 }
999                                 prev = current;
1000                         }
1001                         return adjustmentRules;
1002                 }
1003
1004 #if LIBC || MONODROID
1005                 private static bool ValidTZFile (byte [] buffer, int length)
1006                 {
1007                         StringBuilder magic = new StringBuilder ();
1008
1009                         for (int i = 0; i < 4; i++)
1010                                 magic.Append ((char)buffer [i]);
1011                         
1012                         if (magic.ToString () != "TZif")
1013                                 return false;
1014
1015                         if (length >= BUFFER_SIZE)
1016                                 return false;
1017
1018                         return true;
1019                 }
1020
1021                 static int SwapInt32 (int i)
1022                 {
1023                         return (((i >> 24) & 0xff)
1024                                 | ((i >> 8) & 0xff00)
1025                                 | ((i << 8) & 0xff0000)
1026                                 | ((i << 24)));
1027                 }
1028
1029                 static int ReadBigEndianInt32 (byte [] buffer, int start)
1030                 {
1031                         int i = BitConverter.ToInt32 (buffer, start);
1032                         if (!BitConverter.IsLittleEndian)
1033                                 return i;
1034
1035                         return SwapInt32 (i);
1036                 }
1037
1038                 private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
1039                 {
1040                         //Reading the header. 4 bytes for magic, 16 are reserved
1041                         int ttisgmtcnt = ReadBigEndianInt32 (buffer, 20);
1042                         int ttisstdcnt = ReadBigEndianInt32 (buffer, 24);
1043                         int leapcnt = ReadBigEndianInt32 (buffer, 28);
1044                         int timecnt = ReadBigEndianInt32 (buffer, 32);
1045                         int typecnt = ReadBigEndianInt32 (buffer, 36);
1046                         int charcnt = ReadBigEndianInt32 (buffer, 40);
1047
1048                         if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
1049                                 throw new InvalidTimeZoneException ();
1050
1051                         Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
1052                         Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
1053                         List<KeyValuePair<DateTime, TimeType>> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
1054
1055                         if (time_types.Count == 0)
1056                                 throw new InvalidTimeZoneException ();
1057
1058                         if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
1059                                 throw new InvalidTimeZoneException ();
1060
1061                         TimeSpan baseUtcOffset = new TimeSpan (0);
1062                         TimeSpan dstDelta = new TimeSpan (0);
1063                         string standardDisplayName = null;
1064                         string daylightDisplayName = null;
1065                         bool dst_observed = false;
1066                         DateTime dst_start = DateTime.MinValue;
1067                         List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
1068
1069                         for (int i = 0; i < transitions.Count; i++) {
1070                                 var pair = transitions [i];
1071                                 DateTime ttime = pair.Key;
1072                                 TimeType ttype = pair.Value;
1073                                 if (!ttype.IsDst) {
1074                                         if (standardDisplayName != ttype.Name || baseUtcOffset.TotalSeconds != ttype.Offset) {
1075                                                 standardDisplayName = ttype.Name;
1076                                                 daylightDisplayName = null;
1077                                                 baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
1078                                                 adjustmentRules = new List<AdjustmentRule> ();
1079                                                 dst_observed = false;
1080                                         }
1081                                         if (dst_observed) {
1082                                                 //FIXME: check additional fields for this:
1083                                                 //most of the transitions are expressed in GMT 
1084                                                 dst_start += baseUtcOffset;
1085                                                 DateTime dst_end = ttime + baseUtcOffset + dstDelta;
1086
1087                                                 //some weird timezone (America/Phoenix) have end dates on Jan 1st
1088                                                 if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
1089                                                         dst_end -= new TimeSpan (24, 0, 0);
1090
1091                                                 DateTime dateStart, dateEnd;
1092                                                 if (dst_start.Month < 7)
1093                                                         dateStart = new DateTime (dst_start.Year, 1, 1);
1094                                                 else
1095                                                         dateStart = new DateTime (dst_start.Year, 7, 1);
1096
1097                                                 if (dst_end.Month >= 7)
1098                                                         dateEnd = new DateTime (dst_end.Year, 12, 31);
1099                                                 else
1100                                                         dateEnd = new DateTime (dst_end.Year, 6, 30);
1101
1102                                                 
1103                                                 TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
1104                                                 TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
1105                                                 if  (transition_start != transition_end) //y, that happened in Argentina in 1943-1946
1106                                                         adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
1107                                         }
1108                                         dst_observed = false;
1109                                 } else {
1110                                         if (daylightDisplayName != ttype.Name || dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds) {
1111                                                 daylightDisplayName = ttype.Name;
1112                                                 dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
1113                                         }
1114                                         dst_start = ttime;
1115                                         dst_observed = true;
1116                                 }
1117                         }
1118
1119                         if (adjustmentRules.Count == 0) {
1120                                 TimeType t = (TimeType)time_types [0];
1121                                 if (standardDisplayName == null) {
1122                                         standardDisplayName = t.Name;
1123                                         baseUtcOffset = new TimeSpan (0, 0, t.Offset);
1124                                 }
1125                                 return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
1126                         } else {
1127                                 return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, ValidateRules (adjustmentRules).ToArray ());
1128                         }
1129                 }
1130
1131                 static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
1132                 {
1133                         var abbrevs = new Dictionary<int, string> ();
1134                         int abbrev_index = 0;
1135                         var sb = new StringBuilder ();
1136                         for (int i = 0; i < count; i++) {
1137                                 char c = (char) buffer [index + i];
1138                                 if (c != '\0')
1139                                         sb.Append (c);
1140                                 else {
1141                                         abbrevs.Add (abbrev_index, sb.ToString ());
1142                                         //Adding all the substrings too, as it seems to be used, at least for Africa/Windhoek
1143                                         for (int j = 1; j < sb.Length; j++)
1144                                                 abbrevs.Add (abbrev_index + j, sb.ToString (j, sb.Length - j));
1145                                         abbrev_index = i + 1;
1146                                         sb = new StringBuilder ();
1147                                 }
1148                         }
1149                         return abbrevs;
1150                 }
1151
1152                 static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
1153                 {
1154                         var types = new Dictionary<int, TimeType> (count);
1155                         for (int i = 0; i < count; i++) {
1156                                 int offset = ReadBigEndianInt32 (buffer, index + 6 * i);
1157                                 byte is_dst = buffer [index + 6 * i + 4];
1158                                 byte abbrev = buffer [index + 6 * i + 5];
1159                                 types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
1160                         }
1161                         return types;
1162                 }
1163
1164                 static List<KeyValuePair<DateTime, TimeType>> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
1165                 {
1166                         var list = new List<KeyValuePair<DateTime, TimeType>> (count);
1167                         for (int i = 0; i < count; i++) {
1168                                 int unixtime = ReadBigEndianInt32 (buffer, index + 4 * i);
1169                                 DateTime ttime = DateTimeFromUnixTime (unixtime);
1170                                 byte ttype = buffer [index + 4 * count + i];
1171                                 list.Add (new KeyValuePair<DateTime, TimeType> (ttime, time_types [(int)ttype]));
1172                         }
1173                         return list;
1174                 }
1175
1176                 static DateTime DateTimeFromUnixTime (long unix_time)
1177                 {
1178                         DateTime date_time = new DateTime (1970, 1, 1);
1179                         return date_time.AddSeconds (unix_time);
1180                 }
1181         }
1182
1183         struct TimeType {
1184                 public readonly int Offset;
1185                 public readonly bool IsDst;
1186                 public string Name;
1187
1188                 public TimeType (int offset, bool is_dst, string abbrev)
1189                 {
1190                         this.Offset = offset;
1191                         this.IsDst = is_dst;
1192                         this.Name = abbrev;
1193                 }
1194
1195                 public override string ToString ()
1196                 {
1197                         return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;
1198                 }
1199 #else
1200         }
1201 #endif
1202         }
1203 }
1204
1205 #endif