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