Fixed TimeZoneInfo.Local on windows xp
[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 #if MOBILE
49         [TypeForwardedFrom (Consts.AssemblySystem_Core)]
50 #else
51         [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
52 #endif
53         [SerializableAttribute]
54         public
55         sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
56         {
57                 TimeSpan baseUtcOffset;
58                 public TimeSpan BaseUtcOffset {
59                         get { return baseUtcOffset; }
60                 }
61
62                 string daylightDisplayName;
63                 public string DaylightName {
64                         get { 
65                                 return supportsDaylightSavingTime
66                                         ? daylightDisplayName
67                                         : string.Empty;
68                         }
69                 }
70
71                 string displayName;
72                 public string DisplayName {
73                         get { return displayName; }
74                 }
75
76                 string id;
77                 public string Id {
78                         get { return id; }
79                 }
80
81                 static TimeZoneInfo local;
82                 public static TimeZoneInfo Local {
83                         get { 
84                                 var l = local;
85                                 if (l == null) {
86                                         l = CreateLocal ();
87                                         if (l == null)
88                                                 throw new TimeZoneNotFoundException ();
89
90                                         if (Interlocked.CompareExchange (ref local, l, null) != null)
91                                                 l = local;
92                                 }
93
94                                 return l;
95                         }
96                 }
97
98                 /*
99                         TimeZone transitions are stored when there is a change on the base offset.
100                 */
101                 private List<KeyValuePair<DateTime, TimeType>> transitions;
102
103                 static TimeZoneInfo CreateLocal ()
104                 {
105 #if MONODROID
106                         return AndroidTimeZones.Local;
107 #elif MONOTOUCH
108                         using (Stream stream = GetMonoTouchData (null)) {
109                                 return BuildFromStream ("Local", stream);
110                         }
111 #else
112 #if !NET_2_1
113                         if (IsWindows && LocalZoneKey != null) {
114                                 string name = (string)LocalZoneKey.GetValue ("TimeZoneKeyName");
115                                 if (name == null)
116                                         name = (string)LocalZoneKey.GetValue ("StandardName"); // windows xp
117                                 name = TrimSpecial (name);
118                                 if (name != null)
119                                         return TimeZoneInfo.FindSystemTimeZoneById (name);
120                         }
121 #endif
122
123                         var tz = Environment.GetEnvironmentVariable ("TZ");
124                         if (tz != null) {
125                                 if (tz == String.Empty)
126                                         return Utc;
127                                 try {
128                                         return FindSystemTimeZoneByFileName (tz, Path.Combine (TimeZoneDirectory, tz));
129                                 } catch {
130                                         return Utc;
131                                 }
132                         }
133
134                         try {
135                                 return FindSystemTimeZoneByFileName ("Local", "/etc/localtime");        
136                         } catch {
137                                 try {
138                                         return FindSystemTimeZoneByFileName ("Local", Path.Combine (TimeZoneDirectory, "localtime"));   
139                                 } catch {
140                                         return null;
141                                 }
142                         }
143 #endif
144                 }
145
146                 string standardDisplayName;
147                 public string StandardName {
148                         get { return standardDisplayName; }
149                 }
150
151                 bool supportsDaylightSavingTime;
152                 public bool SupportsDaylightSavingTime {
153                         get  { return supportsDaylightSavingTime; }
154                 }
155
156                 static TimeZoneInfo utc;
157                 public static TimeZoneInfo Utc {
158                         get {
159                                 if (utc == null)
160                                         utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
161                                 return utc;
162                         }
163                 }
164 #if LIBC
165                 static string timeZoneDirectory;
166                 static string TimeZoneDirectory {
167                         get {
168                                 if (timeZoneDirectory == null)
169                                         timeZoneDirectory = "/usr/share/zoneinfo";
170                                 return timeZoneDirectory;
171                         }
172                         set {
173                                 ClearCachedData ();
174                                 timeZoneDirectory = value;
175                         }
176                 }
177 #endif
178                 private AdjustmentRule [] adjustmentRules;
179
180 #if !NET_2_1
181                 /// <summary>
182                 /// Determine whether windows of not (taken Stephane Delcroix's code)
183                 /// </summary>
184                 private static bool IsWindows
185                 {
186                         get {
187                                 int platform = (int) Environment.OSVersion.Platform;
188                                 return ((platform != 4) && (platform != 6) && (platform != 128));
189                         }
190                 }
191                 
192                 /// <summary>
193                 /// Needed to trim misc garbage in MS registry keys
194                 /// </summary>
195                 private static string TrimSpecial (string str)
196                 {
197                         var Istart = 0;
198                         while (Istart < str.Length && !char.IsLetterOrDigit(str[Istart])) Istart++;
199                         var Iend = str.Length - 1;
200                         while (Iend > Istart && !char.IsLetterOrDigit(str[Iend])) Iend--;
201                         
202                         return str.Substring (Istart, Iend-Istart+1);
203                 }
204                 
205                 static RegistryKey timeZoneKey;
206                 static RegistryKey TimeZoneKey {
207                         get {
208                                 if (timeZoneKey != null)
209                                         return timeZoneKey;
210                                 if (!IsWindows)
211                                         return null;
212                                 
213                                 return timeZoneKey = Registry.LocalMachine.OpenSubKey (
214                                         "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
215                                         false);
216                         }
217                 }
218                 
219                 static RegistryKey localZoneKey;
220                 static RegistryKey LocalZoneKey {
221                         get {
222                                 if (localZoneKey != null)
223                                         return localZoneKey;
224                                 
225                                 if (!IsWindows)
226                                         return null;
227                                 
228                                 return localZoneKey = Registry.LocalMachine.OpenSubKey (
229                                         "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation", false);
230                         }
231                 }
232 #endif
233
234                 public static void ClearCachedData ()
235                 {
236                         local = null;
237                         utc = null;
238                         systemTimeZones = null;
239                 }
240
241                 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
242                 {
243                         return ConvertTime (dateTime, dateTime.Kind == DateTimeKind.Utc ? TimeZoneInfo.Utc : TimeZoneInfo.Local, destinationTimeZone);
244                 }
245
246                 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
247                 {
248                         if (sourceTimeZone == null)
249                                 throw new ArgumentNullException ("sourceTimeZone");
250
251                         if (destinationTimeZone == null)
252                                 throw new ArgumentNullException ("destinationTimeZone");
253                         
254                         if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
255                                 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
256
257                         if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
258                                 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
259                         
260                         if (sourceTimeZone.IsInvalidTime (dateTime))
261                                 throw new ArgumentException ("dateTime parameter is an invalid time");
262
263                         if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
264                                 return dateTime;
265
266                         DateTime utc = ConvertTimeToUtc (dateTime, sourceTimeZone);
267
268                         if (destinationTimeZone != TimeZoneInfo.Utc) {
269                                 utc = ConvertTimeFromUtc (utc, destinationTimeZone);
270                                 if (dateTime.Kind == DateTimeKind.Unspecified)
271                                         return DateTime.SpecifyKind (utc, DateTimeKind.Unspecified);
272                         }
273                         
274                         return utc;
275                 }
276
277                 public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) 
278                 {
279                         if (destinationTimeZone == null) 
280                                 throw new ArgumentNullException("destinationTimeZone");
281                 
282                         var utcDateTime = dateTimeOffset.UtcDateTime;
283                         AdjustmentRule rule = destinationTimeZone.GetApplicableRule (utcDateTime);
284                 
285                         if (rule != null && destinationTimeZone.IsDaylightSavingTime(utcDateTime)) {
286                                 var offset = destinationTimeZone.BaseUtcOffset + rule.DaylightDelta;
287                                 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + offset, offset);
288                         }
289                         else {
290                                 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + destinationTimeZone.BaseUtcOffset, destinationTimeZone.BaseUtcOffset);
291                         }
292                 }
293
294                 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
295                 {
296                         return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
297                 }
298
299                 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
300                 {
301                         return ConvertTime (dateTime, FindSystemTimeZoneById (sourceTimeZoneId), FindSystemTimeZoneById (destinationTimeZoneId));
302                 }
303
304                 public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
305                 {
306                         return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
307                 }
308
309                 private DateTime ConvertTimeFromUtc (DateTime dateTime)
310                 {
311                         if (dateTime.Kind == DateTimeKind.Local)
312                                 throw new ArgumentException ("Kind property of dateTime is Local");
313
314                         if (this == TimeZoneInfo.Utc)
315                                 return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
316                         
317                         //FIXME: do not rely on DateTime implementation !
318                         if (this == TimeZoneInfo.Local) 
319                         {
320                                 return dateTime.ToLocalTime ();
321                         }
322
323
324                         AdjustmentRule rule = GetApplicableRule (dateTime);
325                         if (rule != null && IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
326                                 return DateTime.SpecifyKind (dateTime + BaseUtcOffset + rule.DaylightDelta , DateTimeKind.Unspecified);
327                         else
328                                 return DateTime.SpecifyKind (dateTime + BaseUtcOffset, DateTimeKind.Unspecified);
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                         if (sourceTimeZone.IsAmbiguousTime (dateTime) || !sourceTimeZone.IsDaylightSavingTime (dateTime)) {
377                                 var ticks = dateTime.Ticks - sourceTimeZone.BaseUtcOffset.Ticks;
378                                 if (ticks < DateTime.MinValue.Ticks)
379                                         ticks = DateTime.MinValue.Ticks;
380                                 else if (ticks > DateTime.MaxValue.Ticks)
381                                         ticks = DateTime.MaxValue.Ticks;
382
383                                 return new DateTime (ticks, DateTimeKind.Utc);
384                         }
385                         
386                                 AdjustmentRule rule = sourceTimeZone.GetApplicableRule (dateTime);
387                                 if (rule != null)
388                                         return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
389                                 else
390                                         return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
391                         
392                 }
393
394                 static internal TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out Boolean isAmbiguousLocalDst)
395                 {
396                         bool isDaylightSavings;
397                         return GetUtcOffsetFromUtc(time, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst);
398                 }
399
400                 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName) 
401                 {
402                         return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
403                 }
404
405                 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
406                 {
407                         return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
408                 }
409
410                 public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
411                 {
412                         return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
413                 }
414
415                 public override bool Equals (object obj)
416                 {
417                         return Equals (obj as TimeZoneInfo);
418                 }
419
420                 public bool Equals (TimeZoneInfo other)
421                 {
422                         if (other == null)
423                                 return false;
424
425                         return other.Id == this.Id && HasSameRules (other);
426                 }
427
428                 public static TimeZoneInfo FindSystemTimeZoneById (string id)
429                 {
430                         //FIXME: this method should check for cached values in systemTimeZones
431                         if (id == null)
432                                 throw new ArgumentNullException ("id");
433 #if !NET_2_1
434                         if (TimeZoneKey != null)
435                         {
436                                 RegistryKey key = TimeZoneKey.OpenSubKey (id, false);
437                                 if (key == null)
438                                         throw new TimeZoneNotFoundException ();
439                                 return FromRegistryKey(id, key);
440                         }
441 #endif
442                         // Local requires special logic that already exists in the Local property (bug #326)
443                         if (id == "Local")
444                                 return Local;
445 #if MONOTOUCH
446                         using (Stream stream = GetMonoTouchData (id)) {
447                                 return BuildFromStream (id, stream);
448                         }
449 #elif MONODROID
450                         var timeZoneInfo = AndroidTimeZones.GetTimeZone (id, id);
451                         if (timeZoneInfo == null)
452                                 throw new TimeZoneNotFoundException ();
453                         return timeZoneInfo;
454 #elif LIBC
455                         string filepath = Path.Combine (TimeZoneDirectory, id);
456                         return FindSystemTimeZoneByFileName (id, filepath);
457 #else
458                         throw new NotImplementedException ();
459 #endif
460                 }
461
462 #if LIBC
463                 private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
464                 {
465                         if (!File.Exists (filepath))
466                                 throw new TimeZoneNotFoundException ();
467
468                         using (FileStream stream = File.OpenRead (filepath)) {
469                                 return BuildFromStream (id, stream);
470                         }
471                 }
472 #endif
473 #if LIBC || MONOTOUCH
474                 const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
475                 
476                 private static TimeZoneInfo BuildFromStream (string id, Stream stream) 
477                 {
478                         byte [] buffer = new byte [BUFFER_SIZE];
479                         int length = stream.Read (buffer, 0, BUFFER_SIZE);
480                         
481                         if (!ValidTZFile (buffer, length))
482                                 throw new InvalidTimeZoneException ("TZ file too big for the buffer");
483
484                         try {
485                                 return ParseTZBuffer (id, buffer, length);
486                         } catch (Exception e) {
487                                 throw new InvalidTimeZoneException (e.Message);
488                         }
489                 }
490 #endif
491
492 #if !NET_2_1
493                 private static TimeZoneInfo FromRegistryKey (string id, RegistryKey key)
494                 {
495                         byte [] reg_tzi = (byte []) key.GetValue ("TZI");
496
497                         if (reg_tzi == null)
498                                 throw new InvalidTimeZoneException ();
499
500                         int bias = BitConverter.ToInt32 (reg_tzi, 0);
501                         TimeSpan baseUtcOffset = new TimeSpan (0, -bias, 0);
502
503                         string display_name = (string) key.GetValue ("Display");
504                         string standard_name = (string) key.GetValue ("Std");
505                         string daylight_name = (string) key.GetValue ("Dlt");
506
507                         List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
508
509                         RegistryKey dst_key = key.OpenSubKey ("Dynamic DST", false);
510                         if (dst_key != null) {
511                                 int first_year = (int) dst_key.GetValue ("FirstEntry");
512                                 int last_year = (int) dst_key.GetValue ("LastEntry");
513                                 int year;
514
515                                 for (year=first_year; year<=last_year; year++) {
516                                         byte [] dst_tzi = (byte []) dst_key.GetValue (year.ToString ());
517                                         if (dst_tzi != null) {
518                                                 int start_year = year == first_year ? 1 : year;
519                                                 int end_year = year == last_year ? 9999 : year;
520                                                 ParseRegTzi(adjustmentRules, start_year, end_year, dst_tzi);
521                                         }
522                                 }
523                         }
524                         else
525                                 ParseRegTzi(adjustmentRules, 1, 9999, reg_tzi);
526
527                         return CreateCustomTimeZone (id, baseUtcOffset, display_name, standard_name, daylight_name, ValidateRules (adjustmentRules).ToArray ());
528                 }
529
530                 private static void ParseRegTzi (List<AdjustmentRule> adjustmentRules, int start_year, int end_year, byte [] buffer)
531                 {
532                         //int standard_bias = BitConverter.ToInt32 (buffer, 4); /* not sure how to handle this */
533                         int daylight_bias = BitConverter.ToInt32 (buffer, 8);
534
535                         int standard_year = BitConverter.ToInt16 (buffer, 12);
536                         int standard_month = BitConverter.ToInt16 (buffer, 14);
537                         int standard_dayofweek = BitConverter.ToInt16 (buffer, 16);
538                         int standard_day = BitConverter.ToInt16 (buffer, 18);
539                         int standard_hour = BitConverter.ToInt16 (buffer, 20);
540                         int standard_minute = BitConverter.ToInt16 (buffer, 22);
541                         int standard_second = BitConverter.ToInt16 (buffer, 24);
542                         int standard_millisecond = BitConverter.ToInt16 (buffer, 26);
543
544                         int daylight_year = BitConverter.ToInt16 (buffer, 28);
545                         int daylight_month = BitConverter.ToInt16 (buffer, 30);
546                         int daylight_dayofweek = BitConverter.ToInt16 (buffer, 32);
547                         int daylight_day = BitConverter.ToInt16 (buffer, 34);
548                         int daylight_hour = BitConverter.ToInt16 (buffer, 36);
549                         int daylight_minute = BitConverter.ToInt16 (buffer, 38);
550                         int daylight_second = BitConverter.ToInt16 (buffer, 40);
551                         int daylight_millisecond = BitConverter.ToInt16 (buffer, 42);
552
553                         if (standard_month == 0 || daylight_month == 0)
554                                 return;
555
556                         DateTime start_date;
557                         DateTime start_timeofday = new DateTime (1, 1, 1, daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
558                         TransitionTime start_transition_time;
559
560                         if (daylight_year == 0) {
561                                 start_date = new DateTime (start_year, 1, 1);
562                                 start_transition_time = TransitionTime.CreateFloatingDateRule (
563                                         start_timeofday, daylight_month, daylight_day,
564                                         (DayOfWeek) daylight_dayofweek);
565                         }
566                         else {
567                                 start_date = new DateTime (daylight_year, daylight_month, daylight_day,
568                                         daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
569                                 start_transition_time = TransitionTime.CreateFixedDateRule (
570                                         start_timeofday, daylight_month, daylight_day);
571                         }
572
573                         DateTime end_date;
574                         DateTime end_timeofday = new DateTime (1, 1, 1, standard_hour, standard_minute, standard_second, standard_millisecond);
575                         TransitionTime end_transition_time;
576
577                         if (standard_year == 0) {
578                                 end_date = new DateTime (end_year, 12, 31);
579                                 end_transition_time = TransitionTime.CreateFloatingDateRule (
580                                         end_timeofday, standard_month, standard_day,
581                                         (DayOfWeek) standard_dayofweek);
582                         }
583                         else {
584                                 end_date = new DateTime (standard_year, standard_month, standard_day,
585                                         standard_hour, standard_minute, standard_second, standard_millisecond);
586                                 end_transition_time = TransitionTime.CreateFixedDateRule (
587                                         end_timeofday, standard_month, standard_day);
588                         }
589
590                         TimeSpan daylight_delta = new TimeSpan(0, -daylight_bias, 0);
591
592                         adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (
593                                 start_date, end_date, daylight_delta,
594                                 start_transition_time, end_transition_time));
595                 }
596 #endif
597
598                 public AdjustmentRule [] GetAdjustmentRules ()
599                 {
600                         if (!supportsDaylightSavingTime)
601                                 return new AdjustmentRule [0];
602                         else
603                                 return (AdjustmentRule []) adjustmentRules.Clone ();
604                 }
605
606                 public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
607                 {
608                         if (!IsAmbiguousTime (dateTime))
609                                 throw new ArgumentException ("dateTime is not an ambiguous time");
610
611                         AdjustmentRule rule = GetApplicableRule (dateTime);
612                         if (rule != null)
613                                 return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
614                         else
615                                 return new TimeSpan[] {baseUtcOffset, baseUtcOffset};
616                 }
617
618                 public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
619                 {
620                         if (!IsAmbiguousTime (dateTimeOffset))
621                                 throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
622
623                         throw new NotImplementedException ();
624                 }
625
626                 public override int GetHashCode ()
627                 {
628                         int hash_code = Id.GetHashCode ();
629                         foreach (AdjustmentRule rule in GetAdjustmentRules ())
630                                 hash_code ^= rule.GetHashCode ();
631                         return hash_code;
632                 }
633
634                 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
635                 {
636                         if (info == null)
637                                 throw new ArgumentNullException ("info");
638                         info.AddValue ("Id", id);
639                         info.AddValue ("DisplayName", displayName);
640                         info.AddValue ("StandardName", standardDisplayName);
641                         info.AddValue ("DaylightName", daylightDisplayName);
642                         info.AddValue ("BaseUtcOffset", baseUtcOffset);
643                         info.AddValue ("AdjustmentRules", adjustmentRules);
644                         info.AddValue ("SupportsDaylightSavingTime", SupportsDaylightSavingTime);
645                 }
646
647                 //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
648                 private static List<TimeZoneInfo> systemTimeZones;
649                 public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
650                 {
651                         if (systemTimeZones == null) {
652                                 systemTimeZones = new List<TimeZoneInfo> ();
653 #if !NET_2_1
654                                 if (TimeZoneKey != null) {
655                                         foreach (string id in TimeZoneKey.GetSubKeyNames ()) {
656                                                 try {
657                                                         systemTimeZones.Add (FindSystemTimeZoneById (id));
658                                                 } catch {}
659                                         }
660
661                                         return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
662                                 }
663 #endif
664 #if MONODROID
665                         foreach (string id in AndroidTimeZones.GetAvailableIds ()) {
666                                 var tz = AndroidTimeZones.GetTimeZone (id, id);
667                                 if (tz != null)
668                                         systemTimeZones.Add (tz);
669                         }
670 #elif MONOTOUCH
671                                 if (systemTimeZones.Count == 0) {
672                                         foreach (string name in GetMonoTouchNames ()) {
673                                                 using (Stream stream = GetMonoTouchData (name, false)) {
674                                                         if (stream == null)
675                                                                 continue;
676                                                         systemTimeZones.Add (BuildFromStream (name, stream));
677                                                 }
678                                         }
679                                 }
680 #elif LIBC
681                                 string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
682                                 foreach (string continent in continents) {
683                                         try {
684                                                 foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
685                                                         try {
686                                                                 string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
687                                                                 systemTimeZones.Add (FindSystemTimeZoneById (id));
688                                                         } catch (ArgumentNullException) {
689                                                         } catch (TimeZoneNotFoundException) {
690                                                         } catch (InvalidTimeZoneException) {
691                                                         } catch (Exception) {
692                                                                 throw;
693                                                         }
694                                                 }
695                                         } catch {}
696                                 }
697 #else
698                                 throw new NotImplementedException ("This method is not implemented for this platform");
699 #endif
700                         }
701                         return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
702                 }
703
704                 public TimeSpan GetUtcOffset (DateTime dateTime)
705                 {
706                         bool isDST;
707                         return GetUtcOffset (dateTime, out isDST);
708                 }
709
710                 public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
711                 {
712                         throw new NotImplementedException ();
713                 }
714
715                 private TimeSpan GetUtcOffset (DateTime dateTime, out bool isDST)
716                 {
717                         isDST = false;
718
719                         TimeZoneInfo tz = this;
720                         if (dateTime.Kind == DateTimeKind.Utc)
721                                 tz = TimeZoneInfo.Utc;
722
723                         if (dateTime.Kind == DateTimeKind.Local)
724                                 tz = TimeZoneInfo.Local;
725
726                         bool isTzDst;
727                         var tzOffset = GetUtcOffset (dateTime, tz, out isTzDst);
728
729                         if (tz == this) {
730                                 isDST = isTzDst;
731                                 return tzOffset;
732                         }
733
734                         var utcTicks = dateTime.Ticks - tzOffset.Ticks;
735                         if (utcTicks < 0 || utcTicks > DateTime.MaxValue.Ticks)
736                                 return BaseUtcOffset;
737
738                         var utcDateTime = new DateTime (utcTicks, DateTimeKind.Utc);
739
740                         return GetUtcOffset (utcDateTime, this, out isDST);
741                 }
742
743                 private static TimeSpan GetUtcOffset (DateTime dateTime, TimeZoneInfo tz, out bool isDST)
744                 {
745                         if (dateTime.Kind == DateTimeKind.Local && tz != TimeZoneInfo.Local)
746                                 throw new Exception ();
747
748                         isDST = false;
749
750                         if (tz == TimeZoneInfo.Utc)
751                                 return TimeSpan.Zero;
752
753                         TimeSpan offset;
754                         if (tz.TryGetTransitionOffset(dateTime, out offset, out isDST))
755                                 return offset;
756
757                         if (dateTime.Kind == DateTimeKind.Utc) {
758                                 var utcRule = tz.GetApplicableRule (dateTime);
759                                 if (utcRule != null && tz.IsInDST (utcRule, dateTime)) {
760                                         isDST = true;
761                                         return tz.BaseUtcOffset + utcRule.DaylightDelta;
762                                 }
763
764                                 return tz.BaseUtcOffset;
765                         }
766
767                         var stdTicks = dateTime.Ticks - tz.BaseUtcOffset.Ticks;
768                         if (stdTicks < 0 || stdTicks > DateTime.MaxValue.Ticks)
769                                 return tz.BaseUtcOffset;
770
771                         var stdUtcDateTime = new DateTime (stdTicks, DateTimeKind.Utc);
772                         var tzRule = tz.GetApplicableRule (stdUtcDateTime);
773
774                         DateTime dstUtcDateTime = DateTime.MinValue;
775                         if (tzRule != null) {
776                                 var dstTicks = stdUtcDateTime.Ticks - tzRule.DaylightDelta.Ticks;
777                                 if (dstTicks < 0 || dstTicks > DateTime.MaxValue.Ticks)
778                                         return tz.BaseUtcOffset;
779
780                                 dstUtcDateTime = new DateTime (dstTicks, DateTimeKind.Utc);
781                         }
782
783                         if (tzRule != null && tz.IsInDST (tzRule, stdUtcDateTime) && tz.IsInDST (tzRule, dstUtcDateTime)) {
784                                 isDST = true;
785                                 return tz.BaseUtcOffset + tzRule.DaylightDelta;
786                         }
787
788                         return tz.BaseUtcOffset;
789                 }
790
791                 public bool HasSameRules (TimeZoneInfo other)
792                 {
793                         if (other == null)
794                                 throw new ArgumentNullException ("other");
795
796                         if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
797                                 return false;
798
799                         if (this.adjustmentRules == null)
800                                 return true;
801
802                         if (this.BaseUtcOffset != other.BaseUtcOffset)
803                                 return false;
804
805                         if (this.adjustmentRules.Length != other.adjustmentRules.Length)
806                                 return false;
807
808                         for (int i = 0; i < adjustmentRules.Length; i++) {
809                                 if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
810                                         return false;
811                         }
812                         
813                         return true;
814                 }
815
816                 public bool IsAmbiguousTime (DateTime dateTime)
817                 {
818                         if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
819                                 throw new ArgumentException ("Kind is Local and time is Invalid");
820
821                         if (this == TimeZoneInfo.Utc)
822                                 return false;
823                         
824                         if (dateTime.Kind == DateTimeKind.Utc)
825                                 dateTime = ConvertTimeFromUtc (dateTime);
826
827                         if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
828                                 dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
829
830                         AdjustmentRule rule = GetApplicableRule (dateTime);
831                         if (rule != null) {
832                                 DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
833                                 if (dateTime > tpoint - rule.DaylightDelta  && dateTime <= tpoint)
834                                         return true;
835                         }
836                                 
837                         return false;
838                 }
839
840                 public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
841                 {
842                         throw new NotImplementedException ();
843                 }
844
845                 private bool IsInDST (AdjustmentRule rule, DateTime dateTime)
846                 {
847                         // Check whether we're in the dateTime year's DST period
848                         if (IsInDSTForYear (rule, dateTime, dateTime.Year))
849                                 return true;
850
851                         // We might be in the dateTime previous year's DST period
852                         return IsInDSTForYear (rule, dateTime, dateTime.Year - 1);
853                 }
854
855                 bool IsInDSTForYear (AdjustmentRule rule, DateTime dateTime, int year)
856                 {
857                         DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, year);
858                         DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
859                         if (dateTime.Kind == DateTimeKind.Utc) {
860                                 DST_start -= BaseUtcOffset;
861                                 DST_end -= (BaseUtcOffset + rule.DaylightDelta);
862                         }
863
864                         return (dateTime >= DST_start && dateTime < DST_end);
865                 }
866                 
867                 public bool IsDaylightSavingTime (DateTime dateTime)
868                 {
869                         if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
870                                 throw new ArgumentException ("dateTime is invalid and Kind is Local");
871
872                         if (this == TimeZoneInfo.Utc)
873                                 return false;
874                         
875                         if (!SupportsDaylightSavingTime)
876                                 return false;
877
878                         bool isDst;
879                         GetUtcOffset (dateTime, out isDst);
880
881                         return isDst;
882                 }
883
884                 internal bool IsDaylightSavingTime (DateTime dateTime, TimeZoneInfoOptions flags)
885                 {
886                         return IsDaylightSavingTime (dateTime);
887                 }
888
889                 public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
890                 {
891                         throw new NotImplementedException ();
892                 }
893
894                 void IDeserializationCallback.OnDeserialization (object sender)
895                 {
896                         try {
897                                         TimeZoneInfo.Validate (id, baseUtcOffset, adjustmentRules);
898                                 } catch (ArgumentException ex) {
899                                         throw new SerializationException ("invalid serialization data", ex);
900                                 }
901                 }
902
903                 private static void Validate (string id, TimeSpan baseUtcOffset, AdjustmentRule [] adjustmentRules)
904                 {
905                         if (id == null)
906                                 throw new ArgumentNullException ("id");
907
908                         if (id == String.Empty)
909                                 throw new ArgumentException ("id parameter is an empty string");
910
911                         if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
912                                 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
913
914                         if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
915                                 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
916
917 #if STRICT
918                         if (id.Length > 32)
919                                 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
920 #endif
921
922                         if (adjustmentRules != null && adjustmentRules.Length != 0) {
923                                 AdjustmentRule prev = null;
924                                 foreach (AdjustmentRule current in adjustmentRules) {
925                                         if (current == null)
926                                                 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
927
928                                         if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
929                                                         (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
930                                                 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;");
931
932                                         if (prev != null && prev.DateStart > current.DateStart)
933                                                 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
934                                         
935                                         if (prev != null && prev.DateEnd > current.DateStart)
936                                                 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
937
938                                         if (prev != null && prev.DateEnd == current.DateStart)
939                                                 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
940
941                                         prev = current;
942                                 }
943                         }
944                 }
945                 
946                 public override string ToString ()
947                 {
948                         return DisplayName;
949                 }
950
951                 private TimeZoneInfo (SerializationInfo info, StreamingContext context)
952                 {
953                         if (info == null)
954                                 throw new ArgumentNullException ("info");
955                         id = (string) info.GetValue ("Id", typeof (string));
956                         displayName = (string) info.GetValue ("DisplayName", typeof (string));
957                         standardDisplayName = (string) info.GetValue ("StandardName", typeof (string));
958                         daylightDisplayName = (string) info.GetValue ("DaylightName", typeof (string));
959                         baseUtcOffset = (TimeSpan) info.GetValue ("BaseUtcOffset", typeof (TimeSpan));
960                         adjustmentRules = (TimeZoneInfo.AdjustmentRule []) info.GetValue ("AdjustmentRules", typeof (TimeZoneInfo.AdjustmentRule []));
961                         supportsDaylightSavingTime = (bool) info.GetValue ("SupportsDaylightSavingTime", typeof (bool));
962                 }
963
964                 private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
965                 {
966                         if (id == null)
967                                 throw new ArgumentNullException ("id");
968
969                         if (id == String.Empty)
970                                 throw new ArgumentException ("id parameter is an empty string");
971
972                         if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
973                                 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
974
975                         if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
976                                 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
977
978 #if STRICT
979                         if (id.Length > 32)
980                                 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
981 #endif
982
983                         bool supportsDaylightSavingTime = !disableDaylightSavingTime;
984
985                         if (adjustmentRules != null && adjustmentRules.Length != 0) {
986                                 AdjustmentRule prev = null;
987                                 foreach (AdjustmentRule current in adjustmentRules) {
988                                         if (current == null)
989                                                 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
990
991                                         if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
992                                                         (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
993                                                 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;");
994
995                                         if (prev != null && prev.DateStart > current.DateStart)
996                                                 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
997                                         
998                                         if (prev != null && prev.DateEnd > current.DateStart)
999                                                 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
1000
1001                                         if (prev != null && prev.DateEnd == current.DateStart)
1002                                                 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
1003
1004                                         prev = current;
1005                                 }
1006                         } else {
1007                                 supportsDaylightSavingTime = false;
1008                         }
1009                         
1010                         this.id = id;
1011                         this.baseUtcOffset = baseUtcOffset;
1012                         this.displayName = displayName ?? id;
1013                         this.standardDisplayName = standardDisplayName ?? id;
1014                         this.daylightDisplayName = daylightDisplayName;
1015                         this.supportsDaylightSavingTime = supportsDaylightSavingTime;
1016                         this.adjustmentRules = adjustmentRules;
1017                 }
1018
1019                 private AdjustmentRule GetApplicableRule (DateTime dateTime)
1020                 {
1021                         //Applicable rules are in standard time
1022                         DateTime date = dateTime;
1023
1024                         if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
1025                                 date = date.ToUniversalTime () + BaseUtcOffset;
1026                         else if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
1027                                 date = date + BaseUtcOffset;
1028
1029                         // get the date component of the datetime
1030                         date = date.Date;
1031
1032                         if (adjustmentRules != null) {
1033                                 foreach (AdjustmentRule rule in adjustmentRules) {
1034                                         if (rule.DateStart > date)
1035                                                 return null;
1036                                         if (rule.DateEnd < date)
1037                                                 continue;
1038                                         return rule;
1039                                 }
1040                         }
1041                         return null;
1042                 }
1043
1044                 private bool TryGetTransitionOffset (DateTime dateTime, out TimeSpan offset,out bool isDst)
1045                 {
1046                         offset = BaseUtcOffset;
1047                         isDst = false;
1048
1049                         if (transitions == null)
1050                                 return false;
1051
1052                         //Transitions are in UTC
1053                         DateTime date = dateTime;
1054
1055                         if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local) {
1056                                 var ticks = date.ToUniversalTime ().Ticks + BaseUtcOffset.Ticks;
1057                                 if (ticks < DateTime.MinValue.Ticks || ticks > DateTime.MaxValue.Ticks)
1058                                         return false;
1059
1060                                 date = new DateTime (ticks, DateTimeKind.Utc);
1061                         }
1062
1063                         if (dateTime.Kind != DateTimeKind.Utc) {
1064                                 var ticks = date.Ticks - BaseUtcOffset.Ticks;
1065                                 if (ticks < DateTime.MinValue.Ticks || ticks > DateTime.MaxValue.Ticks)
1066                                         return false;
1067
1068                                 date = new DateTime (ticks, DateTimeKind.Utc);
1069                         }
1070
1071                         for (var i =  transitions.Count - 1; i >= 0; i--) {
1072                                 var pair = transitions [i];
1073                                 DateTime ttime = pair.Key;
1074                                 TimeType ttype = pair.Value;
1075
1076                                 if (ttime > date)
1077                                         continue;
1078
1079                                 offset =  new TimeSpan (0, 0, ttype.Offset);
1080                                 isDst = ttype.IsDst;
1081
1082                                 return true;
1083                         }
1084
1085                         return false;
1086                 }
1087
1088                 private static DateTime TransitionPoint (TransitionTime transition, int year)
1089                 {
1090                         if (transition.IsFixedDateRule)
1091                                 return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
1092
1093                         DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
1094                         int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first + 7) % 7;
1095                         if (day >  DateTime.DaysInMonth (year, transition.Month))
1096                                 day -= 7;
1097                         if (day < 1)
1098                                 day += 7;
1099                         return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
1100                 }
1101
1102                 static List<AdjustmentRule> ValidateRules (List<AdjustmentRule> adjustmentRules)
1103                 {
1104                         AdjustmentRule prev = null;
1105                         foreach (AdjustmentRule current in adjustmentRules.ToArray ()) {
1106                                 if (prev != null && prev.DateEnd > current.DateStart) {
1107                                         adjustmentRules.Remove (current);
1108                                 }
1109                                 prev = current;
1110                         }
1111                         return adjustmentRules;
1112                 }
1113
1114 #if LIBC || MONODROID
1115                 private static bool ValidTZFile (byte [] buffer, int length)
1116                 {
1117                         StringBuilder magic = new StringBuilder ();
1118
1119                         for (int i = 0; i < 4; i++)
1120                                 magic.Append ((char)buffer [i]);
1121                         
1122                         if (magic.ToString () != "TZif")
1123                                 return false;
1124
1125                         if (length >= BUFFER_SIZE)
1126                                 return false;
1127
1128                         return true;
1129                 }
1130
1131                 static int SwapInt32 (int i)
1132                 {
1133                         return (((i >> 24) & 0xff)
1134                                 | ((i >> 8) & 0xff00)
1135                                 | ((i << 8) & 0xff0000)
1136                                 | ((i << 24)));
1137                 }
1138
1139                 static int ReadBigEndianInt32 (byte [] buffer, int start)
1140                 {
1141                         int i = BitConverter.ToInt32 (buffer, start);
1142                         if (!BitConverter.IsLittleEndian)
1143                                 return i;
1144
1145                         return SwapInt32 (i);
1146                 }
1147
1148                 private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
1149                 {
1150                         //Reading the header. 4 bytes for magic, 16 are reserved
1151                         int ttisgmtcnt = ReadBigEndianInt32 (buffer, 20);
1152                         int ttisstdcnt = ReadBigEndianInt32 (buffer, 24);
1153                         int leapcnt = ReadBigEndianInt32 (buffer, 28);
1154                         int timecnt = ReadBigEndianInt32 (buffer, 32);
1155                         int typecnt = ReadBigEndianInt32 (buffer, 36);
1156                         int charcnt = ReadBigEndianInt32 (buffer, 40);
1157
1158                         if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
1159                                 throw new InvalidTimeZoneException ();
1160
1161                         Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
1162                         Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
1163                         List<KeyValuePair<DateTime, TimeType>> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
1164
1165                         if (time_types.Count == 0)
1166                                 throw new InvalidTimeZoneException ();
1167
1168                         if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
1169                                 throw new InvalidTimeZoneException ();
1170
1171                         TimeSpan baseUtcOffset = new TimeSpan (0);
1172                         TimeSpan dstDelta = new TimeSpan (0);
1173                         string standardDisplayName = null;
1174                         string daylightDisplayName = null;
1175                         bool dst_observed = false;
1176                         DateTime dst_start = DateTime.MinValue;
1177                         List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
1178                         bool storeTransition = false;
1179
1180                         for (int i = 0; i < transitions.Count; i++) {
1181                                 var pair = transitions [i];
1182                                 DateTime ttime = pair.Key;
1183                                 TimeType ttype = pair.Value;
1184                                 if (!ttype.IsDst) {
1185                                         if (standardDisplayName != ttype.Name)
1186                                                 standardDisplayName = ttype.Name;
1187                                         if (baseUtcOffset.TotalSeconds != ttype.Offset) {
1188                                                 baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
1189                                                 if (adjustmentRules.Count > 0) // We ignore AdjustmentRules but store transitions.
1190                                                         storeTransition = true;
1191                                                 adjustmentRules = new List<AdjustmentRule> ();
1192                                                 dst_observed = false;
1193                                         }
1194                                         if (dst_observed) {
1195                                                 //FIXME: check additional fields for this:
1196                                                 //most of the transitions are expressed in GMT 
1197                                                 dst_start += baseUtcOffset;
1198                                                 DateTime dst_end = ttime + baseUtcOffset + dstDelta;
1199
1200                                                 //some weird timezone (America/Phoenix) have end dates on Jan 1st
1201                                                 if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
1202                                                         dst_end -= new TimeSpan (24, 0, 0);
1203
1204                                                 DateTime dateStart, dateEnd;
1205                                                 if (dst_start.Month < 7)
1206                                                         dateStart = new DateTime (dst_start.Year, 1, 1);
1207                                                 else
1208                                                         dateStart = new DateTime (dst_start.Year, 7, 1);
1209
1210                                                 if (dst_end.Month >= 7)
1211                                                         dateEnd = new DateTime (dst_end.Year, 12, 31);
1212                                                 else
1213                                                         dateEnd = new DateTime (dst_end.Year, 6, 30);
1214
1215                                                 
1216                                                 TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
1217                                                 TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
1218                                                 if  (transition_start != transition_end) //y, that happened in Argentina in 1943-1946
1219                                                         adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
1220                                         }
1221                                         dst_observed = false;
1222                                 } else {
1223                                         if (daylightDisplayName != ttype.Name)
1224                                                 daylightDisplayName = ttype.Name;
1225                                         if (dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds)
1226                                                 dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
1227
1228                                         dst_start = ttime;
1229                                         dst_observed = true;
1230                                 }
1231                         }
1232
1233                         TimeZoneInfo tz;
1234                         if (adjustmentRules.Count == 0 && !storeTransition) {
1235                                 TimeType t = (TimeType)time_types [0];
1236                                 if (standardDisplayName == null) {
1237                                         standardDisplayName = t.Name;
1238                                         baseUtcOffset = new TimeSpan (0, 0, t.Offset);
1239                                 }
1240                                 tz = CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
1241                         } else {
1242                                 tz = CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, ValidateRules (adjustmentRules).ToArray ());
1243                         }
1244
1245                         if (storeTransition)
1246                                 tz.transitions = transitions;
1247
1248                         return tz;
1249                 }
1250
1251                 static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
1252                 {
1253                         var abbrevs = new Dictionary<int, string> ();
1254                         int abbrev_index = 0;
1255                         var sb = new StringBuilder ();
1256                         for (int i = 0; i < count; i++) {
1257                                 char c = (char) buffer [index + i];
1258                                 if (c != '\0')
1259                                         sb.Append (c);
1260                                 else {
1261                                         abbrevs.Add (abbrev_index, sb.ToString ());
1262                                         //Adding all the substrings too, as it seems to be used, at least for Africa/Windhoek
1263                                         for (int j = 1; j < sb.Length; j++)
1264                                                 abbrevs.Add (abbrev_index + j, sb.ToString (j, sb.Length - j));
1265                                         abbrev_index = i + 1;
1266                                         sb = new StringBuilder ();
1267                                 }
1268                         }
1269                         return abbrevs;
1270                 }
1271
1272                 static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
1273                 {
1274                         var types = new Dictionary<int, TimeType> (count);
1275                         for (int i = 0; i < count; i++) {
1276                                 int offset = ReadBigEndianInt32 (buffer, index + 6 * i);
1277                                 byte is_dst = buffer [index + 6 * i + 4];
1278                                 byte abbrev = buffer [index + 6 * i + 5];
1279                                 types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
1280                         }
1281                         return types;
1282                 }
1283
1284                 static List<KeyValuePair<DateTime, TimeType>> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
1285                 {
1286                         var list = new List<KeyValuePair<DateTime, TimeType>> (count);
1287                         for (int i = 0; i < count; i++) {
1288                                 int unixtime = ReadBigEndianInt32 (buffer, index + 4 * i);
1289                                 DateTime ttime = DateTimeFromUnixTime (unixtime);
1290                                 byte ttype = buffer [index + 4 * count + i];
1291                                 list.Add (new KeyValuePair<DateTime, TimeType> (ttime, time_types [(int)ttype]));
1292                         }
1293                         return list;
1294                 }
1295
1296                 static DateTime DateTimeFromUnixTime (long unix_time)
1297                 {
1298                         DateTime date_time = new DateTime (1970, 1, 1);
1299                         return date_time.AddSeconds (unix_time);
1300                 }
1301
1302 #region reference sources
1303         // Shortcut for TimeZoneInfo.Local.GetUtcOffset
1304         internal static TimeSpan GetLocalUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags)
1305         {
1306             bool dst;
1307             return Local.GetUtcOffset (dateTime, out dst);
1308         }
1309
1310         internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags)
1311         {
1312             bool dst;
1313             return GetUtcOffset (dateTime, out dst);
1314         }
1315
1316         // used by GetUtcOffsetFromUtc (DateTime.Now, DateTime.ToLocalTime) for max/min whole-day range checks
1317         private static DateTime s_maxDateOnly = new DateTime(9999, 12, 31);
1318         private static DateTime s_minDateOnly = new DateTime(1, 1, 2);
1319
1320         static internal TimeSpan GetUtcOffsetFromUtc (DateTime time, TimeZoneInfo zone, out Boolean isDaylightSavings, out Boolean isAmbiguousLocalDst)
1321         {
1322             isDaylightSavings = false;
1323             isAmbiguousLocalDst = false;
1324             TimeSpan baseOffset = zone.BaseUtcOffset;
1325             Int32 year;
1326             AdjustmentRule rule;
1327
1328             if (time > s_maxDateOnly) {
1329                 rule = zone.GetAdjustmentRuleForTime(DateTime.MaxValue);
1330                 year = 9999;
1331             }
1332             else if (time < s_minDateOnly) {
1333                 rule = zone.GetAdjustmentRuleForTime(DateTime.MinValue);
1334                 year = 1;
1335             }
1336             else {
1337                 DateTime targetTime = time + baseOffset;
1338                 year = time.Year;
1339                 rule = zone.GetAdjustmentRuleForTime(targetTime);
1340             }
1341
1342             if (rule != null) {
1343                 isDaylightSavings = GetIsDaylightSavingsFromUtc(time, year, zone.baseUtcOffset, rule, out isAmbiguousLocalDst);
1344                 baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* */);
1345             }
1346
1347             return baseOffset;
1348         }
1349
1350         // assumes dateTime is in the current time zone's time
1351         private AdjustmentRule GetAdjustmentRuleForTime(DateTime dateTime) {
1352             if (adjustmentRules == null || adjustmentRules.Length == 0) {
1353                 return null;
1354             }
1355
1356 #if WINXP_AND_WIN2K3_SUPPORT
1357             // On pre-Vista versions of Windows if you run "cmd /c date" or "cmd /c time" to update the system time
1358             // the operating system doesn't pick up the correct time zone adjustment rule (it stays on the currently loaded rule).
1359             // We need to use the OS API data in this scenario instead of the loaded adjustment rules from the registry for
1360             // consistency.  Otherwise DateTime.Now might not match the time displayed in the system tray.              
1361             if (!Environment.IsWindowsVistaOrAbove && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local) {
1362                 return s_cachedData.GetOneYearLocalFromLocal(dateTime.Year).rule;
1363             }
1364 #endif
1365             // Only check the whole-date portion of the dateTime -
1366             // This is because the AdjustmentRule DateStart & DateEnd are stored as
1367             // Date-only values {4/2/2006 - 10/28/2006} but actually represent the
1368             // time span {4/2/2006@00:00:00.00000 - 10/28/2006@23:59:59.99999}
1369             DateTime date = dateTime.Date;
1370
1371             for (int i = 0; i < adjustmentRules.Length; i++) {
1372                 if (adjustmentRules[i].DateStart <= date && adjustmentRules[i].DateEnd >= date) {
1373                     return adjustmentRules[i];
1374                 }
1375             }
1376
1377             return null;
1378         }
1379
1380         //
1381         // GetIsDaylightSavingsFromUtc -
1382         //
1383         // Helper function that checks if a given dateTime is in Daylight Saving Time (DST)
1384         // This function assumes the dateTime is in UTC and AdjustmentRule is in a different time zone
1385         //
1386         static private Boolean GetIsDaylightSavingsFromUtc(DateTime time, Int32 Year, TimeSpan utc, AdjustmentRule rule, out Boolean isAmbiguousLocalDst) {
1387             isAmbiguousLocalDst = false;
1388
1389             if (rule == null) {
1390                 return false;
1391             }
1392
1393             // Get the daylight changes for the year of the specified time.
1394             TimeSpan offset = utc; /* */
1395             DaylightTime daylightTime = GetDaylightTime(Year, rule);
1396
1397             // The start and end times represent the range of universal times that are in DST for that year.                
1398             // Within that there is an ambiguous hour, usually right at the end, but at the beginning in
1399             // the unusual case of a negative daylight savings delta.
1400             DateTime startTime = daylightTime.Start - offset;
1401             DateTime endTime = daylightTime.End - offset - rule.DaylightDelta; /* */
1402             DateTime ambiguousStart;
1403             DateTime ambiguousEnd;
1404             if (daylightTime.Delta.Ticks > 0) {
1405                 ambiguousStart = endTime - daylightTime.Delta;
1406                 ambiguousEnd = endTime;
1407             } else {
1408                 ambiguousStart = startTime;
1409                 ambiguousEnd = startTime - daylightTime.Delta;
1410             }
1411
1412             Boolean isDst = CheckIsDst(startTime, time, endTime);
1413
1414             // See if the resulting local time becomes ambiguous. This must be captured here or the
1415             // DateTime will not be able to round-trip back to UTC accurately.
1416             if (isDst) {
1417                 isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
1418
1419                 if (!isAmbiguousLocalDst && ambiguousStart.Year != ambiguousEnd.Year) {
1420                     // there exists an extreme corner case where the start or end period is on a year boundary and
1421                     // because of this the comparison above might have been performed for a year-early or a year-later
1422                     // than it should have been.
1423                     DateTime ambiguousStartModified;
1424                     DateTime ambiguousEndModified;
1425                     try {
1426                         ambiguousStartModified = ambiguousStart.AddYears(1);
1427                         ambiguousEndModified   = ambiguousEnd.AddYears(1);
1428                         isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd); 
1429                     }
1430                     catch (ArgumentOutOfRangeException) {}
1431
1432                     if (!isAmbiguousLocalDst) {
1433                         try {
1434                             ambiguousStartModified = ambiguousStart.AddYears(-1);
1435                             ambiguousEndModified   = ambiguousEnd.AddYears(-1);
1436                             isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
1437                         }
1438                         catch (ArgumentOutOfRangeException) {}
1439                     }
1440
1441                 }
1442             }
1443
1444             return isDst;
1445         }
1446
1447
1448         static private Boolean CheckIsDst(DateTime startTime, DateTime time, DateTime endTime) {
1449             Boolean isDst;
1450
1451             int startTimeYear = startTime.Year;
1452             int endTimeYear = endTime.Year;
1453
1454             if (startTimeYear != endTimeYear) {
1455                 endTime = endTime.AddYears(startTimeYear - endTimeYear);
1456             }
1457
1458             int timeYear = time.Year;
1459
1460             if (startTimeYear != timeYear) {
1461                 time = time.AddYears(startTimeYear - timeYear);
1462             }
1463
1464             if (startTime > endTime) {
1465                 // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year.
1466                 // Note, the summer in the southern hemisphere begins late in the year.
1467                 isDst = (time < endTime || time >= startTime);
1468             }
1469             else {
1470                 // In northern hemisphere, the daylight saving time starts in the middle of the year.
1471                 isDst = (time >= startTime && time < endTime);
1472             }
1473             return isDst;
1474         }
1475
1476         //
1477         // GetDaylightTime -
1478         //
1479         // Helper function that returns a DaylightTime from a year and AdjustmentRule
1480         //
1481         static private DaylightTime GetDaylightTime(Int32 year, AdjustmentRule rule) {
1482             TimeSpan delta = rule.DaylightDelta;
1483             DateTime startTime = TransitionTimeToDateTime(year, rule.DaylightTransitionStart);
1484             DateTime endTime = TransitionTimeToDateTime(year, rule.DaylightTransitionEnd);
1485             return new DaylightTime(startTime, endTime, delta);
1486         }
1487
1488         //
1489         // TransitionTimeToDateTime -
1490         //
1491         // Helper function that converts a year and TransitionTime into a DateTime
1492         //
1493         static private DateTime TransitionTimeToDateTime(Int32 year, TransitionTime transitionTime) {
1494             DateTime value;
1495             DateTime timeOfDay = transitionTime.TimeOfDay;
1496
1497             if (transitionTime.IsFixedDateRule) {
1498                 // create a DateTime from the passed in year and the properties on the transitionTime
1499
1500                 // if the day is out of range for the month then use the last day of the month
1501                 Int32 day = DateTime.DaysInMonth(year, transitionTime.Month);
1502
1503                 value = new DateTime(year, transitionTime.Month, (day < transitionTime.Day) ? day : transitionTime.Day, 
1504                             timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
1505             }
1506             else {
1507                 if (transitionTime.Week <= 4) {
1508                     //
1509                     // Get the (transitionTime.Week)th Sunday.
1510                     //
1511                     value = new DateTime(year, transitionTime.Month, 1,
1512                             timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
1513
1514                     int dayOfWeek = (int)value.DayOfWeek;
1515                     int delta = (int)transitionTime.DayOfWeek - dayOfWeek;
1516                     if (delta < 0) {
1517                         delta += 7;
1518                     }
1519                     delta += 7 * (transitionTime.Week - 1);
1520
1521                     if (delta > 0) {
1522                         value = value.AddDays(delta);
1523                     }
1524                 }
1525                 else {
1526                     //
1527                     // If TransitionWeek is greater than 4, we will get the last week.
1528                     //
1529                     Int32 daysInMonth = DateTime.DaysInMonth(year, transitionTime.Month);
1530                     value = new DateTime(year, transitionTime.Month, daysInMonth,
1531                             timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
1532
1533                     // This is the day of week for the last day of the month.
1534                     int dayOfWeek = (int)value.DayOfWeek;
1535                     int delta = dayOfWeek - (int)transitionTime.DayOfWeek;
1536                     if (delta < 0) {
1537                         delta += 7;
1538                     }
1539
1540                     if (delta > 0) {
1541                         value = value.AddDays(-delta);
1542                     }
1543                 }
1544             }
1545             return value;
1546         }
1547
1548         //
1549         // IsInvalidTime -
1550         //
1551         // returns true when dateTime falls into a "hole in time".
1552         //
1553         public Boolean IsInvalidTime(DateTime dateTime) {
1554             Boolean isInvalid = false;
1555           
1556             if ( (dateTime.Kind == DateTimeKind.Unspecified)
1557             ||   (dateTime.Kind == DateTimeKind.Local && this == Local) ) {
1558
1559                 // only check Unspecified and (Local when this TimeZoneInfo instance is Local)
1560                 AdjustmentRule rule = GetAdjustmentRuleForTime(dateTime);
1561
1562
1563                 if (rule != null) {
1564                     DaylightTime daylightTime = GetDaylightTime(dateTime.Year, rule);
1565                     isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime);
1566                 }
1567                 else {
1568                     isInvalid = false;
1569                 }
1570             }
1571
1572             return isInvalid;
1573         }
1574
1575         //
1576         // GetIsInvalidTime -
1577         //
1578         // Helper function that checks if a given DateTime is in an invalid time ("time hole")
1579         // A "time hole" occurs at a DST transition point when time jumps forward;
1580         // For example, in Pacific Standard Time on Sunday, April 2, 2006 time jumps from
1581         // 1:59:59.9999999 to 3AM.  The time range 2AM to 2:59:59.9999999AM is the "time hole".
1582         // A "time hole" is not limited to only occurring at the start of DST, and may occur at
1583         // the end of DST as well.
1584         //
1585         static private Boolean GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTime daylightTime) {
1586             Boolean isInvalid = false;
1587             if (rule == null || rule.DaylightDelta == TimeSpan.Zero) {
1588                 return isInvalid;
1589             }
1590
1591             DateTime startInvalidTime;
1592             DateTime endInvalidTime;
1593
1594             // if at DST start we transition forward in time then there is an ambiguous time range at the DST end
1595             if (rule.DaylightDelta < TimeSpan.Zero) {
1596                 startInvalidTime = daylightTime.End;
1597                 endInvalidTime = daylightTime.End - rule.DaylightDelta; /* */
1598             }
1599             else {
1600                 startInvalidTime = daylightTime.Start;
1601                 endInvalidTime = daylightTime.Start + rule.DaylightDelta; /* */
1602             }
1603
1604             isInvalid = (time >= startInvalidTime && time < endInvalidTime);
1605
1606             if (!isInvalid && startInvalidTime.Year != endInvalidTime.Year) {
1607                 // there exists an extreme corner case where the start or end period is on a year boundary and
1608                 // because of this the comparison above might have been performed for a year-early or a year-later
1609                 // than it should have been.
1610                 DateTime startModifiedInvalidTime;
1611                 DateTime endModifiedInvalidTime;
1612                 try {
1613                     startModifiedInvalidTime = startInvalidTime.AddYears(1);
1614                     endModifiedInvalidTime   = endInvalidTime.AddYears(1);
1615                     isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
1616                 }
1617                 catch (ArgumentOutOfRangeException) {}
1618
1619                 if (!isInvalid) {
1620                     try {
1621                         startModifiedInvalidTime = startInvalidTime.AddYears(-1);
1622                         endModifiedInvalidTime  = endInvalidTime.AddYears(-1);
1623                         isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
1624                     }
1625                     catch (ArgumentOutOfRangeException) {}
1626                 }
1627             }
1628             return isInvalid;
1629         } 
1630 #endregion
1631         }
1632
1633         struct TimeType {
1634                 public readonly int Offset;
1635                 public readonly bool IsDst;
1636                 public string Name;
1637
1638                 public TimeType (int offset, bool is_dst, string abbrev)
1639                 {
1640                         this.Offset = offset;
1641                         this.IsDst = is_dst;
1642                         this.Name = abbrev;
1643                 }
1644
1645                 public override string ToString ()
1646                 {
1647                         return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;
1648                 }
1649 #else
1650         }
1651 #endif
1652         }
1653 }