Merge pull request #487 from mayerwin/patch-1
[mono.git] / mcs / class / System.Core / System / TimeZoneInfo.cs
index 6be3f8f8aeea342de94dde0b0b3f5f92795bdd6e..3bfcd0c204c62299d4b5d5f0b2e7f4144e032721 100644 (file)
@@ -4,6 +4,8 @@
  * Author(s)
  *     Stephane Delcroix <stephane@delcroix.org>
  *
+ * Copyright 2011 Xamarin Inc.
+ *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of this software and associated documentation files (the
  * "Software"), to deal in the Software without restriction, including
 using System;
 using System.Runtime.CompilerServices;
 
-#if !INSIDE_CORLIB && (NET_4_0 || BOOTSTRAP_NET_4_0 || MOONLIGHT)
+#if !INSIDE_CORLIB && (NET_4_0 || MOONLIGHT || MOBILE)
 
 [assembly:TypeForwardedTo (typeof(TimeZoneInfo))]
 
-#elif NET_3_5 || (MONOTOUCH && !INSIDE_CORLIB) || (MOONLIGHT && INSIDE_CORLIB)
+#elif (INSIDE_CORLIB && (NET_4_0 || MOONLIGHT || MOBILE)) || (!INSIDE_CORLIB && (NET_3_5 && !NET_4_0 && !MOBILE))
 
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.Runtime.Serialization;
 using System.Text;
 
-#if LIBC
+#if LIBC || MONODROID
 using System.IO;
 using Mono;
 #endif
@@ -47,9 +49,9 @@ using Microsoft.Win32;
 
 namespace System
 {
-#if NET_4_0 || BOOTSTRAP_NET_4_0
+#if NET_4_0
        [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
-#elif MOONLIGHT
+#elif MOONLIGHT || MOBILE
        [TypeForwardedFrom (Consts.AssemblySystem_Core)]
 #endif
        [SerializableAttribute]
@@ -63,9 +65,9 @@ namespace System
                string daylightDisplayName;
                public string DaylightName {
                        get { 
-                               if (disableDaylightSavingTime)
-                                       return String.Empty;
-                               return daylightDisplayName; 
+                               return supportsDaylightSavingTime
+                                       ? daylightDisplayName
+                                       : string.Empty;
                        }
                }
 
@@ -83,7 +85,13 @@ namespace System
                public static TimeZoneInfo Local {
                        get { 
                                if (local == null) {
-#if LIBC
+#if MONODROID
+                                       local = ZoneInfoDB.Default;
+#elif MONOTOUCH
+                                       using (Stream stream = GetMonoTouchDefault ()) {
+                                               local = BuildFromStream ("Local", stream);
+                                       }
+#elif LIBC
                                        try {
                                                local = FindSystemTimeZoneByFileName ("Local", "/etc/localtime");       
                                        } catch {
@@ -94,7 +102,15 @@ namespace System
                                                }
                                        }
 #else
-                                       throw new TimeZoneNotFoundException ();
+                                       if (IsWindows && LocalZoneKey != null) {
+                                               string name = (string)LocalZoneKey.GetValue ("TimeZoneKeyName");
+                                               name = TrimSpecial (name);
+                                               if (name != null)
+                                                       local = TimeZoneInfo.FindSystemTimeZoneById (name);
+                                       }
+                                       
+                                       if (local == null)
+                                               throw new TimeZoneNotFoundException ();
 #endif
                                }
                                return local;
@@ -106,9 +122,9 @@ namespace System
                        get { return standardDisplayName; }
                }
 
-               bool disableDaylightSavingTime;
+               bool supportsDaylightSavingTime;
                public bool SupportsDaylightSavingTime {
-                       get  { return !disableDaylightSavingTime; }
+                       get  { return supportsDaylightSavingTime; }
                }
 
                static TimeZoneInfo utc;
@@ -120,7 +136,7 @@ namespace System
                        }
                }
 #if LIBC
-               static string timeZoneDirectory = null;
+               static string timeZoneDirectory;
                static string TimeZoneDirectory {
                        get {
                                if (timeZoneDirectory == null)
@@ -136,20 +152,55 @@ namespace System
                private AdjustmentRule [] adjustmentRules;
 
 #if !NET_2_1
-               static RegistryKey timeZoneKey = null;
-               static bool timeZoneKeySet = false;
+               /// <summary>
+               /// Determine whether windows of not (taken Stephane Delcroix's code)
+               /// </summary>
+               private static bool IsWindows
+               {
+                       get {
+                               int platform = (int) Environment.OSVersion.Platform;
+                               return ((platform != 4) && (platform != 6) && (platform != 128));
+                       }
+               }
+               
+               /// <summary>
+               /// Needed to trim misc garbage in MS registry keys
+               /// </summary>
+               private static string TrimSpecial (string str)
+               {
+                       var Istart = 0;
+                       while (Istart < str.Length && !char.IsLetterOrDigit(str[Istart])) Istart++;
+                       var Iend = str.Length - 1;
+                       while (Iend > Istart && !char.IsLetterOrDigit(str[Iend])) Iend--;
+                       
+                       return str.Substring (Istart, Iend-Istart+1);
+               }
+               
+               static RegistryKey timeZoneKey;
                static RegistryKey TimeZoneKey {
                        get {
-                               if (!timeZoneKeySet) {
-                                       int p = (int) Environment.OSVersion.Platform;
-                                       /* Only use the registry on non-Unix platforms. */
-                                       if ((p != 4) && (p != 6) && (p != 128))
-                                               timeZoneKey = Registry.LocalMachine.OpenSubKey (
-                                                       "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
-                                                       false);
-                                       timeZoneKeySet = true;
-                               }
-                               return timeZoneKey;
+                               if (timeZoneKey != null)
+                                       return timeZoneKey;
+                               if (!IsWindows)
+                                       return null;
+                               
+                               return timeZoneKey = Registry.LocalMachine.OpenSubKey (
+                                       "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
+                                       false);
+                       }
+               }
+               
+               static RegistryKey localZoneKey;
+               static RegistryKey LocalZoneKey {
+                       get {
+                               if (localZoneKey != null)
+                                       return localZoneKey;
+                               
+                               if (!IsWindows)
+                                       return null;
+                               
+                               return localZoneKey = Registry.LocalMachine.OpenSubKey (
+                                       "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation", false);
                        }
                }
 #endif
@@ -169,10 +220,10 @@ namespace System
                public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
                {
                        if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
-                               throw new ArgumentException ("Kind propery of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
+                               throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
 
                        if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
-                               throw new ArgumentException ("Kind propery of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
+                               throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
 
                        if (sourceTimeZone.IsInvalidTime (dateTime))
                                throw new ArgumentException ("dateTime parameter is an invalid time");
@@ -195,9 +246,21 @@ namespace System
 
                }
 
-               public static DateTimeOffset ConvertTime (DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
+               public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) 
                {
-                       throw new NotImplementedException ();
+                       if (destinationTimeZone == null) 
+                               throw new ArgumentNullException("destinationTimeZone");
+               
+                       var utcDateTime = dateTimeOffset.UtcDateTime;
+                       AdjustmentRule rule = GetApplicableRule (utcDateTime);
+               
+                       if (rule != null && destinationTimeZone.IsDaylightSavingTime(utcDateTime)) {
+                               var offset = destinationTimeZone.BaseUtcOffset + rule.DaylightDelta;
+                               return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + offset, offset);
+                       }
+                       else {
+                               return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + destinationTimeZone.BaseUtcOffset, destinationTimeZone.BaseUtcOffset);
+                       }
                }
 
                public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
@@ -229,7 +292,7 @@ namespace System
 
                        AdjustmentRule rule = GetApplicableRule (dateTime);
                
-                       if (IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
+                       if (rule != null && IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
                                return DateTime.SpecifyKind (dateTime + BaseUtcOffset + rule.DaylightDelta , DateTimeKind.Unspecified);
                        else
                                return DateTime.SpecifyKind (dateTime + BaseUtcOffset, DateTimeKind.Unspecified);
@@ -258,10 +321,10 @@ namespace System
                                throw new ArgumentNullException ("sourceTimeZone");
 
                        if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
-                               throw new ArgumentException ("Kind propery of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
+                               throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
 
                        if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
-                               throw new ArgumentException ("Kind propery of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
+                               throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
 
                        if (sourceTimeZone.IsInvalidTime (dateTime))
                                throw new ArgumentException ("dateTime parameter is an invalid time");
@@ -279,7 +342,10 @@ namespace System
                                return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
                        else {
                                AdjustmentRule rule = sourceTimeZone.GetApplicableRule (dateTime);
-                               return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
+                               if (rule != null)
+                                       return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
+                               else
+                                       return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
                        }
                }
 
@@ -298,6 +364,13 @@ namespace System
                        return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
                }
 
+#if NET_4_5
+               public override bool Equals (object obj)
+               {
+                       return Equals (obj as TimeZoneInfo);
+               }
+#endif
+
                public bool Equals (TimeZoneInfo other)
                {
                        if (other == null)
@@ -320,27 +393,47 @@ namespace System
                                return FromRegistryKey(id, key);
                        }
 #endif
-#if LIBC       
+#if MONODROID
+                       var timeZoneInfo = ZoneInfoDB.GetTimeZone (id);
+                       if (timeZoneInfo == null)
+                               throw new TimeZoneNotFoundException ();
+                       return timeZoneInfo;
+#else
+                       // Local requires special logic that already exists in the Local property (bug #326)
+                       if (id == "Local")
+                               return Local;
+#if MONOTOUCH
+                       using (Stream stream = GetMonoTouchData (id)) {
+                               return BuildFromStream (id, stream);
+                       }
+#elif LIBC
                        string filepath = Path.Combine (TimeZoneDirectory, id);
                        return FindSystemTimeZoneByFileName (id, filepath);
 #else
                        throw new NotImplementedException ();
+#endif
 #endif
                }
 
 #if LIBC
-               const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
                private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
                {
                        if (!File.Exists (filepath))
                                throw new TimeZoneNotFoundException ();
 
-                       byte [] buffer = new byte [BUFFER_SIZE];
-                       int length;
                        using (FileStream stream = File.OpenRead (filepath)) {
-                               length = stream.Read (buffer, 0, BUFFER_SIZE);
+                               return BuildFromStream (id, stream);
                        }
-
+               }
+#endif
+#if LIBC || MONOTOUCH
+               const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
+               
+               private static TimeZoneInfo BuildFromStream (string id, Stream stream) 
+               {
+                       byte [] buffer = new byte [BUFFER_SIZE];
+                       int length = stream.Read (buffer, 0, BUFFER_SIZE);
+                       
                        if (!ValidTZFile (buffer, length))
                                throw new InvalidTimeZoneException ("TZ file too big for the buffer");
 
@@ -465,7 +558,7 @@ namespace System
 
                public AdjustmentRule [] GetAdjustmentRules ()
                {
-                       if (disableDaylightSavingTime)
+                       if (!supportsDaylightSavingTime)
                                return new AdjustmentRule [0];
                        else
                                return (AdjustmentRule []) adjustmentRules.Clone ();
@@ -477,7 +570,10 @@ namespace System
                                throw new ArgumentException ("dateTime is not an ambiguous time");
 
                        AdjustmentRule rule = GetApplicableRule (dateTime);
-                       return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
+                       if (rule != null)
+                               return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
+                       else
+                               return new TimeSpan[] {baseUtcOffset, baseUtcOffset};
                }
 
                public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
@@ -506,7 +602,7 @@ namespace System
                }
 
                //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
-               private static List<TimeZoneInfo> systemTimeZones = null;
+               private static List<TimeZoneInfo> systemTimeZones;
                public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
                {
                        if (systemTimeZones == null) {
@@ -522,7 +618,21 @@ namespace System
                                        return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
                                }
 #endif
-#if LIBC
+#if MONODROID
+                       foreach (string id in ZoneInfoDB.GetAvailableIds ()) {
+                               var tz = ZoneInfoDB.GetTimeZone (id);
+                               if (tz != null)
+                                       systemTimeZones.Add (tz);
+                       }
+#elif MONOTOUCH
+                               if (systemTimeZones.Count == 0) {
+                                       foreach (string name in GetMonoTouchNames ()) {
+                                               using (Stream stream = GetMonoTouchData (name)) {
+                                                       systemTimeZones.Add (BuildFromStream (name, stream));
+                                               }
+                                       }
+                               }
+#elif LIBC
                                string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
                                foreach (string continent in continents) {
                                        try {
@@ -550,7 +660,8 @@ namespace System
                {
                        if (IsDaylightSavingTime (dateTime)) {
                                AdjustmentRule rule = GetApplicableRule (dateTime);
-                               return BaseUtcOffset + rule.DaylightDelta;
+                               if (rule != null)
+                                       return BaseUtcOffset + rule.DaylightDelta;
                        }
                        
                        return BaseUtcOffset;
@@ -601,9 +712,11 @@ namespace System
                                dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
 
                        AdjustmentRule rule = GetApplicableRule (dateTime);
-                       DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
-                       if (dateTime > tpoint - rule.DaylightDelta  && dateTime <= tpoint)
-                               return true;
+                       if (rule != null) {
+                               DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
+                               if (dateTime > tpoint - rule.DaylightDelta  && dateTime <= tpoint)
+                                       return true;
+                       }
                                
                        return false;
                }
@@ -658,9 +771,11 @@ namespace System
                                return false;
 
                        AdjustmentRule rule = GetApplicableRule (dateTime);
-                       DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
-                       if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
-                               return true;
+                       if (rule != null) {
+                               DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
+                               if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
+                                       return true;
+                       }
                                
                        return false;
                }
@@ -703,6 +818,8 @@ namespace System
                                throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
 #endif
 
+                       bool supportsDaylightSavingTime = !disableDaylightSavingTime;
+
                        if (adjustmentRules != null && adjustmentRules.Length != 0) {
                                AdjustmentRule prev = null;
                                foreach (AdjustmentRule current in adjustmentRules) {
@@ -724,6 +841,8 @@ namespace System
 
                                        prev = current;
                                }
+                       } else {
+                               supportsDaylightSavingTime = false;
                        }
                        
                        this.id = id;
@@ -731,7 +850,7 @@ namespace System
                        this.displayName = displayName ?? id;
                        this.standardDisplayName = standardDisplayName ?? id;
                        this.daylightDisplayName = daylightDisplayName;
-                       this.disableDaylightSavingTime = disableDaylightSavingTime;
+                       this.supportsDaylightSavingTime = supportsDaylightSavingTime;
                        this.adjustmentRules = adjustmentRules;
                }
 
@@ -782,7 +901,7 @@ namespace System
                        return adjustmentRules;
                }
 
-#if LIBC
+#if LIBC || MONODROID
                private static bool ValidTZFile (byte [] buffer, int length)
                {
                        StringBuilder magic = new StringBuilder ();
@@ -799,25 +918,6 @@ namespace System
                        return true;
                }
 
-               struct TimeType 
-               {
-                       public readonly int Offset;
-                       public readonly bool IsDst;
-                       public string Name;
-
-                       public TimeType (int offset, bool is_dst, string abbrev)
-                       {
-                               this.Offset = offset;
-                               this.IsDst = is_dst;
-                               this.Name = abbrev;
-                       }
-
-                       public override string ToString ()
-                       {
-                               return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;
-                       }
-               }
-
                static int SwapInt32 (int i)
                {
                        return (((i >> 24) & 0xff)
@@ -978,6 +1078,26 @@ namespace System
                        DateTime date_time = new DateTime (1970, 1, 1);
                        return date_time.AddSeconds (unix_time);
                }
+       }
+
+       struct TimeType {
+               public readonly int Offset;
+               public readonly bool IsDst;
+               public string Name;
+
+               public TimeType (int offset, bool is_dst, string abbrev)
+               {
+                       this.Offset = offset;
+                       this.IsDst = is_dst;
+                       this.Name = abbrev;
+               }
+
+               public override string ToString ()
+               {
+                       return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;
+               }
+#else
+       }
 #endif
        }
 }