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