TimeZoneInfo.cs 35 KB

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