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