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