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