TimeZoneInfo.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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. if (disableDaylightSavingTime)
  60. return String.Empty;
  61. return daylightDisplayName;
  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. return 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 disableDaylightSavingTime;
  111. public bool SupportsDaylightSavingTime {
  112. get { return !disableDaylightSavingTime; }
  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 = null;
  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 = null;
  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 = null;
  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 propery 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 propery 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 propery 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 propery 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. public bool Equals (TimeZoneInfo other)
  295. {
  296. if (other == null)
  297. return false;
  298. return other.Id == this.Id && HasSameRules (other);
  299. }
  300. public static TimeZoneInfo FindSystemTimeZoneById (string id)
  301. {
  302. //FIXME: this method should check for cached values in systemTimeZones
  303. if (id == null)
  304. throw new ArgumentNullException ("id");
  305. #if !NET_2_1
  306. if (TimeZoneKey != null)
  307. {
  308. RegistryKey key = TimeZoneKey.OpenSubKey (id, false);
  309. if (key == null)
  310. throw new TimeZoneNotFoundException ();
  311. return FromRegistryKey(id, key);
  312. }
  313. #endif
  314. #if MONODROID
  315. return ZoneInfoDB.GetTimeZone (id);
  316. #else
  317. // Local requires special logic that already exists in the Local property (bug #326)
  318. if (id == "Local")
  319. return Local;
  320. #if MONOTOUCH
  321. using (Stream stream = GetMonoTouchData (id)) {
  322. return BuildFromStream (id, stream);
  323. }
  324. #elif LIBC
  325. string filepath = Path.Combine (TimeZoneDirectory, id);
  326. return FindSystemTimeZoneByFileName (id, filepath);
  327. #else
  328. throw new NotImplementedException ();
  329. #endif
  330. #endif
  331. }
  332. #if LIBC
  333. private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
  334. {
  335. if (!File.Exists (filepath))
  336. throw new TimeZoneNotFoundException ();
  337. using (FileStream stream = File.OpenRead (filepath)) {
  338. return BuildFromStream (id, stream);
  339. }
  340. }
  341. #endif
  342. #if LIBC || MONOTOUCH
  343. const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
  344. private static TimeZoneInfo BuildFromStream (string id, Stream stream)
  345. {
  346. byte [] buffer = new byte [BUFFER_SIZE];
  347. int length = stream.Read (buffer, 0, BUFFER_SIZE);
  348. if (!ValidTZFile (buffer, length))
  349. throw new InvalidTimeZoneException ("TZ file too big for the buffer");
  350. try {
  351. return ParseTZBuffer (id, buffer, length);
  352. } catch (Exception e) {
  353. throw new InvalidTimeZoneException (e.Message);
  354. }
  355. }
  356. #endif
  357. #if !NET_2_1
  358. private static TimeZoneInfo FromRegistryKey (string id, RegistryKey key)
  359. {
  360. byte [] reg_tzi = (byte []) key.GetValue ("TZI");
  361. if (reg_tzi == null)
  362. throw new InvalidTimeZoneException ();
  363. int bias = BitConverter.ToInt32 (reg_tzi, 0);
  364. TimeSpan baseUtcOffset = new TimeSpan (0, -bias, 0);
  365. string display_name = (string) key.GetValue ("Display");
  366. string standard_name = (string) key.GetValue ("Std");
  367. string daylight_name = (string) key.GetValue ("Dlt");
  368. List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
  369. RegistryKey dst_key = key.OpenSubKey ("Dynamic DST", false);
  370. if (dst_key != null) {
  371. int first_year = (int) dst_key.GetValue ("FirstEntry");
  372. int last_year = (int) dst_key.GetValue ("LastEntry");
  373. int year;
  374. for (year=first_year; year<=last_year; year++) {
  375. byte [] dst_tzi = (byte []) dst_key.GetValue (year.ToString ());
  376. if (dst_tzi != null) {
  377. int start_year = year == first_year ? 1 : year;
  378. int end_year = year == last_year ? 9999 : year;
  379. ParseRegTzi(adjustmentRules, start_year, end_year, dst_tzi);
  380. }
  381. }
  382. }
  383. else
  384. ParseRegTzi(adjustmentRules, 1, 9999, reg_tzi);
  385. return CreateCustomTimeZone (id, baseUtcOffset, display_name, standard_name, daylight_name, ValidateRules (adjustmentRules).ToArray ());
  386. }
  387. private static void ParseRegTzi (List<AdjustmentRule> adjustmentRules, int start_year, int end_year, byte [] buffer)
  388. {
  389. //int standard_bias = BitConverter.ToInt32 (buffer, 4); /* not sure how to handle this */
  390. int daylight_bias = BitConverter.ToInt32 (buffer, 8);
  391. int standard_year = BitConverter.ToInt16 (buffer, 12);
  392. int standard_month = BitConverter.ToInt16 (buffer, 14);
  393. int standard_dayofweek = BitConverter.ToInt16 (buffer, 16);
  394. int standard_day = BitConverter.ToInt16 (buffer, 18);
  395. int standard_hour = BitConverter.ToInt16 (buffer, 20);
  396. int standard_minute = BitConverter.ToInt16 (buffer, 22);
  397. int standard_second = BitConverter.ToInt16 (buffer, 24);
  398. int standard_millisecond = BitConverter.ToInt16 (buffer, 26);
  399. int daylight_year = BitConverter.ToInt16 (buffer, 28);
  400. int daylight_month = BitConverter.ToInt16 (buffer, 30);
  401. int daylight_dayofweek = BitConverter.ToInt16 (buffer, 32);
  402. int daylight_day = BitConverter.ToInt16 (buffer, 34);
  403. int daylight_hour = BitConverter.ToInt16 (buffer, 36);
  404. int daylight_minute = BitConverter.ToInt16 (buffer, 38);
  405. int daylight_second = BitConverter.ToInt16 (buffer, 40);
  406. int daylight_millisecond = BitConverter.ToInt16 (buffer, 42);
  407. if (standard_month == 0 || daylight_month == 0)
  408. return;
  409. DateTime start_date;
  410. DateTime start_timeofday = new DateTime (1, 1, 1, daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
  411. TransitionTime start_transition_time;
  412. if (daylight_year == 0) {
  413. start_date = new DateTime (start_year, 1, 1);
  414. start_transition_time = TransitionTime.CreateFloatingDateRule (
  415. start_timeofday, daylight_month, daylight_day,
  416. (DayOfWeek) daylight_dayofweek);
  417. }
  418. else {
  419. start_date = new DateTime (daylight_year, daylight_month, daylight_day,
  420. daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
  421. start_transition_time = TransitionTime.CreateFixedDateRule (
  422. start_timeofday, daylight_month, daylight_day);
  423. }
  424. DateTime end_date;
  425. DateTime end_timeofday = new DateTime (1, 1, 1, standard_hour, standard_minute, standard_second, standard_millisecond);
  426. TransitionTime end_transition_time;
  427. if (standard_year == 0) {
  428. end_date = new DateTime (end_year, 12, 31);
  429. end_transition_time = TransitionTime.CreateFloatingDateRule (
  430. end_timeofday, standard_month, standard_day,
  431. (DayOfWeek) standard_dayofweek);
  432. }
  433. else {
  434. end_date = new DateTime (standard_year, standard_month, standard_day,
  435. standard_hour, standard_minute, standard_second, standard_millisecond);
  436. end_transition_time = TransitionTime.CreateFixedDateRule (
  437. end_timeofday, standard_month, standard_day);
  438. }
  439. TimeSpan daylight_delta = new TimeSpan(0, -daylight_bias, 0);
  440. adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (
  441. start_date, end_date, daylight_delta,
  442. start_transition_time, end_transition_time));
  443. }
  444. #endif
  445. public static TimeZoneInfo FromSerializedString (string source)
  446. {
  447. throw new NotImplementedException ();
  448. }
  449. public AdjustmentRule [] GetAdjustmentRules ()
  450. {
  451. if (disableDaylightSavingTime)
  452. return new AdjustmentRule [0];
  453. else
  454. return (AdjustmentRule []) adjustmentRules.Clone ();
  455. }
  456. public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
  457. {
  458. if (!IsAmbiguousTime (dateTime))
  459. throw new ArgumentException ("dateTime is not an ambiguous time");
  460. AdjustmentRule rule = GetApplicableRule (dateTime);
  461. if (rule != null)
  462. return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
  463. else
  464. return new TimeSpan[] {baseUtcOffset, baseUtcOffset};
  465. }
  466. public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
  467. {
  468. if (!IsAmbiguousTime (dateTimeOffset))
  469. throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
  470. throw new NotImplementedException ();
  471. }
  472. public override int GetHashCode ()
  473. {
  474. int hash_code = Id.GetHashCode ();
  475. foreach (AdjustmentRule rule in GetAdjustmentRules ())
  476. hash_code ^= rule.GetHashCode ();
  477. return hash_code;
  478. }
  479. #if NET_4_0
  480. void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
  481. #else
  482. public void GetObjectData (SerializationInfo info, StreamingContext context)
  483. #endif
  484. {
  485. throw new NotImplementedException ();
  486. }
  487. //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
  488. private static List<TimeZoneInfo> systemTimeZones = null;
  489. public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
  490. {
  491. if (systemTimeZones == null) {
  492. systemTimeZones = new List<TimeZoneInfo> ();
  493. #if !NET_2_1
  494. if (TimeZoneKey != null) {
  495. foreach (string id in TimeZoneKey.GetSubKeyNames ()) {
  496. try {
  497. systemTimeZones.Add (FindSystemTimeZoneById (id));
  498. } catch {}
  499. }
  500. return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
  501. }
  502. #endif
  503. #if MONODROID
  504. foreach (string id in ZoneInfoDB.GetAvailableIds ()) {
  505. systemTimeZones.Add (ZoneInfoDB.GetTimeZone (id));
  506. }
  507. #elif MONOTOUCH
  508. if (systemTimeZones.Count == 0) {
  509. foreach (string name in GetMonoTouchNames ()) {
  510. using (Stream stream = GetMonoTouchData (name)) {
  511. systemTimeZones.Add (BuildFromStream (name, stream));
  512. }
  513. }
  514. }
  515. #elif LIBC
  516. string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
  517. foreach (string continent in continents) {
  518. try {
  519. foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
  520. try {
  521. string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
  522. systemTimeZones.Add (FindSystemTimeZoneById (id));
  523. } catch (ArgumentNullException) {
  524. } catch (TimeZoneNotFoundException) {
  525. } catch (InvalidTimeZoneException) {
  526. } catch (Exception) {
  527. throw;
  528. }
  529. }
  530. } catch {}
  531. }
  532. #else
  533. throw new NotImplementedException ("This method is not implemented for this platform");
  534. #endif
  535. }
  536. return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
  537. }
  538. public TimeSpan GetUtcOffset (DateTime dateTime)
  539. {
  540. if (IsDaylightSavingTime (dateTime)) {
  541. AdjustmentRule rule = GetApplicableRule (dateTime);
  542. if (rule != null)
  543. return BaseUtcOffset + rule.DaylightDelta;
  544. }
  545. return BaseUtcOffset;
  546. }
  547. public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
  548. {
  549. throw new NotImplementedException ();
  550. }
  551. public bool HasSameRules (TimeZoneInfo other)
  552. {
  553. if (other == null)
  554. throw new ArgumentNullException ("other");
  555. if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
  556. return false;
  557. if (this.adjustmentRules == null)
  558. return true;
  559. if (this.BaseUtcOffset != other.BaseUtcOffset)
  560. return false;
  561. if (this.adjustmentRules.Length != other.adjustmentRules.Length)
  562. return false;
  563. for (int i = 0; i < adjustmentRules.Length; i++) {
  564. if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
  565. return false;
  566. }
  567. return true;
  568. }
  569. public bool IsAmbiguousTime (DateTime dateTime)
  570. {
  571. if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
  572. throw new ArgumentException ("Kind is Local and time is Invalid");
  573. if (this == TimeZoneInfo.Utc)
  574. return false;
  575. if (dateTime.Kind == DateTimeKind.Utc)
  576. dateTime = ConvertTimeFromUtc (dateTime);
  577. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
  578. dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
  579. AdjustmentRule rule = GetApplicableRule (dateTime);
  580. if (rule != null) {
  581. DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
  582. if (dateTime > tpoint - rule.DaylightDelta && dateTime <= tpoint)
  583. return true;
  584. }
  585. return false;
  586. }
  587. public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
  588. {
  589. throw new NotImplementedException ();
  590. }
  591. public bool IsDaylightSavingTime (DateTime dateTime)
  592. {
  593. if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
  594. throw new ArgumentException ("dateTime is invalid and Kind is Local");
  595. if (this == TimeZoneInfo.Utc)
  596. return false;
  597. if (!SupportsDaylightSavingTime)
  598. return false;
  599. //FIXME: do not rely on DateTime implementation !
  600. if ((dateTime.Kind == DateTimeKind.Local || dateTime.Kind == DateTimeKind.Unspecified) && this == TimeZoneInfo.Local)
  601. return dateTime.IsDaylightSavingTime ();
  602. //FIXME: do not rely on DateTime implementation !
  603. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Utc)
  604. return IsDaylightSavingTime (DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc));
  605. AdjustmentRule rule = GetApplicableRule (dateTime.Date);
  606. if (rule == null)
  607. return false;
  608. DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
  609. DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
  610. if (dateTime.Kind == DateTimeKind.Utc) {
  611. DST_start -= BaseUtcOffset;
  612. DST_end -= (BaseUtcOffset + rule.DaylightDelta);
  613. }
  614. return (dateTime >= DST_start && dateTime < DST_end);
  615. }
  616. public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
  617. {
  618. throw new NotImplementedException ();
  619. }
  620. public bool IsInvalidTime (DateTime dateTime)
  621. {
  622. if (dateTime.Kind == DateTimeKind.Utc)
  623. return false;
  624. if (dateTime.Kind == DateTimeKind.Local && this != Local)
  625. return false;
  626. AdjustmentRule rule = GetApplicableRule (dateTime);
  627. if (rule != null) {
  628. DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
  629. if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
  630. return true;
  631. }
  632. return false;
  633. }
  634. #if NET_4_0
  635. void IDeserializationCallback.OnDeserialization (object sender)
  636. #else
  637. public void OnDeserialization (object sender)
  638. #endif
  639. {
  640. throw new NotImplementedException ();
  641. }
  642. public string ToSerializedString ()
  643. {
  644. throw new NotImplementedException ();
  645. }
  646. public override string ToString ()
  647. {
  648. return DisplayName;
  649. }
  650. private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
  651. {
  652. if (id == null)
  653. throw new ArgumentNullException ("id");
  654. if (id == String.Empty)
  655. throw new ArgumentException ("id parameter is an empty string");
  656. if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
  657. throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
  658. if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
  659. throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
  660. #if STRICT
  661. if (id.Length > 32)
  662. throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
  663. #endif
  664. if (adjustmentRules != null && adjustmentRules.Length != 0) {
  665. AdjustmentRule prev = null;
  666. foreach (AdjustmentRule current in adjustmentRules) {
  667. if (current == null)
  668. throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
  669. if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
  670. (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
  671. 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;");
  672. if (prev != null && prev.DateStart > current.DateStart)
  673. throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
  674. if (prev != null && prev.DateEnd > current.DateStart)
  675. throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
  676. if (prev != null && prev.DateEnd == current.DateStart)
  677. throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
  678. prev = current;
  679. }
  680. }
  681. this.id = id;
  682. this.baseUtcOffset = baseUtcOffset;
  683. this.displayName = displayName ?? id;
  684. this.standardDisplayName = standardDisplayName ?? id;
  685. this.daylightDisplayName = daylightDisplayName;
  686. this.disableDaylightSavingTime = disableDaylightSavingTime;
  687. this.adjustmentRules = adjustmentRules;
  688. }
  689. private AdjustmentRule GetApplicableRule (DateTime dateTime)
  690. {
  691. //Transitions are always in standard time
  692. DateTime date = dateTime;
  693. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
  694. date = date.ToUniversalTime () + BaseUtcOffset;
  695. if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
  696. date = date + BaseUtcOffset;
  697. if (adjustmentRules != null) {
  698. foreach (AdjustmentRule rule in adjustmentRules) {
  699. if (rule.DateStart > date.Date)
  700. return null;
  701. if (rule.DateEnd < date.Date)
  702. continue;
  703. return rule;
  704. }
  705. }
  706. return null;
  707. }
  708. private static DateTime TransitionPoint (TransitionTime transition, int year)
  709. {
  710. if (transition.IsFixedDateRule)
  711. return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
  712. DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
  713. int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first) % 7;
  714. if (day > DateTime.DaysInMonth (year, transition.Month))
  715. day -= 7;
  716. return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
  717. }
  718. static List<AdjustmentRule> ValidateRules (List<AdjustmentRule> adjustmentRules)
  719. {
  720. AdjustmentRule prev = null;
  721. foreach (AdjustmentRule current in adjustmentRules.ToArray ()) {
  722. if (prev != null && prev.DateEnd > current.DateStart) {
  723. adjustmentRules.Remove (current);
  724. }
  725. prev = current;
  726. }
  727. return adjustmentRules;
  728. }
  729. #if LIBC || MONODROID
  730. private static bool ValidTZFile (byte [] buffer, int length)
  731. {
  732. StringBuilder magic = new StringBuilder ();
  733. for (int i = 0; i < 4; i++)
  734. magic.Append ((char)buffer [i]);
  735. if (magic.ToString () != "TZif")
  736. return false;
  737. if (length >= BUFFER_SIZE)
  738. return false;
  739. return true;
  740. }
  741. static int SwapInt32 (int i)
  742. {
  743. return (((i >> 24) & 0xff)
  744. | ((i >> 8) & 0xff00)
  745. | ((i << 8) & 0xff0000)
  746. | ((i << 24)));
  747. }
  748. static int ReadBigEndianInt32 (byte [] buffer, int start)
  749. {
  750. int i = BitConverter.ToInt32 (buffer, start);
  751. if (!BitConverter.IsLittleEndian)
  752. return i;
  753. return SwapInt32 (i);
  754. }
  755. private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
  756. {
  757. //Reading the header. 4 bytes for magic, 16 are reserved
  758. int ttisgmtcnt = ReadBigEndianInt32 (buffer, 20);
  759. int ttisstdcnt = ReadBigEndianInt32 (buffer, 24);
  760. int leapcnt = ReadBigEndianInt32 (buffer, 28);
  761. int timecnt = ReadBigEndianInt32 (buffer, 32);
  762. int typecnt = ReadBigEndianInt32 (buffer, 36);
  763. int charcnt = ReadBigEndianInt32 (buffer, 40);
  764. if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
  765. throw new InvalidTimeZoneException ();
  766. Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
  767. Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
  768. List<KeyValuePair<DateTime, TimeType>> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
  769. if (time_types.Count == 0)
  770. throw new InvalidTimeZoneException ();
  771. if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
  772. throw new InvalidTimeZoneException ();
  773. TimeSpan baseUtcOffset = new TimeSpan (0);
  774. TimeSpan dstDelta = new TimeSpan (0);
  775. string standardDisplayName = null;
  776. string daylightDisplayName = null;
  777. bool dst_observed = false;
  778. DateTime dst_start = DateTime.MinValue;
  779. List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
  780. for (int i = 0; i < transitions.Count; i++) {
  781. var pair = transitions [i];
  782. DateTime ttime = pair.Key;
  783. TimeType ttype = pair.Value;
  784. if (!ttype.IsDst) {
  785. if (standardDisplayName != ttype.Name || baseUtcOffset.TotalSeconds != ttype.Offset) {
  786. standardDisplayName = ttype.Name;
  787. daylightDisplayName = null;
  788. baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
  789. adjustmentRules = new List<AdjustmentRule> ();
  790. dst_observed = false;
  791. }
  792. if (dst_observed) {
  793. //FIXME: check additional fields for this:
  794. //most of the transitions are expressed in GMT
  795. dst_start += baseUtcOffset;
  796. DateTime dst_end = ttime + baseUtcOffset + dstDelta;
  797. //some weird timezone (America/Phoenix) have end dates on Jan 1st
  798. if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
  799. dst_end -= new TimeSpan (24, 0, 0);
  800. DateTime dateStart, dateEnd;
  801. if (dst_start.Month < 7)
  802. dateStart = new DateTime (dst_start.Year, 1, 1);
  803. else
  804. dateStart = new DateTime (dst_start.Year, 7, 1);
  805. if (dst_end.Month >= 7)
  806. dateEnd = new DateTime (dst_end.Year, 12, 31);
  807. else
  808. dateEnd = new DateTime (dst_end.Year, 6, 30);
  809. TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
  810. TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
  811. if (transition_start != transition_end) //y, that happened in Argentina in 1943-1946
  812. adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
  813. }
  814. dst_observed = false;
  815. } else {
  816. if (daylightDisplayName != ttype.Name || dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds) {
  817. daylightDisplayName = ttype.Name;
  818. dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
  819. }
  820. dst_start = ttime;
  821. dst_observed = true;
  822. }
  823. }
  824. if (adjustmentRules.Count == 0) {
  825. TimeType t = (TimeType)time_types [0];
  826. if (standardDisplayName == null) {
  827. standardDisplayName = t.Name;
  828. baseUtcOffset = new TimeSpan (0, 0, t.Offset);
  829. }
  830. return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
  831. } else {
  832. return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, ValidateRules (adjustmentRules).ToArray ());
  833. }
  834. }
  835. static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
  836. {
  837. var abbrevs = new Dictionary<int, string> ();
  838. int abbrev_index = 0;
  839. var sb = new StringBuilder ();
  840. for (int i = 0; i < count; i++) {
  841. char c = (char) buffer [index + i];
  842. if (c != '\0')
  843. sb.Append (c);
  844. else {
  845. abbrevs.Add (abbrev_index, sb.ToString ());
  846. //Adding all the substrings too, as it seems to be used, at least for Africa/Windhoek
  847. for (int j = 1; j < sb.Length; j++)
  848. abbrevs.Add (abbrev_index + j, sb.ToString (j, sb.Length - j));
  849. abbrev_index = i + 1;
  850. sb = new StringBuilder ();
  851. }
  852. }
  853. return abbrevs;
  854. }
  855. static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
  856. {
  857. var types = new Dictionary<int, TimeType> (count);
  858. for (int i = 0; i < count; i++) {
  859. int offset = ReadBigEndianInt32 (buffer, index + 6 * i);
  860. byte is_dst = buffer [index + 6 * i + 4];
  861. byte abbrev = buffer [index + 6 * i + 5];
  862. types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
  863. }
  864. return types;
  865. }
  866. static List<KeyValuePair<DateTime, TimeType>> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
  867. {
  868. var list = new List<KeyValuePair<DateTime, TimeType>> (count);
  869. for (int i = 0; i < count; i++) {
  870. int unixtime = ReadBigEndianInt32 (buffer, index + 4 * i);
  871. DateTime ttime = DateTimeFromUnixTime (unixtime);
  872. byte ttype = buffer [index + 4 * count + i];
  873. list.Add (new KeyValuePair<DateTime, TimeType> (ttime, time_types [(int)ttype]));
  874. }
  875. return list;
  876. }
  877. static DateTime DateTimeFromUnixTime (long unix_time)
  878. {
  879. DateTime date_time = new DateTime (1970, 1, 1);
  880. return date_time.AddSeconds (unix_time);
  881. }
  882. }
  883. struct TimeType {
  884. public readonly int Offset;
  885. public readonly bool IsDst;
  886. public string Name;
  887. public TimeType (int offset, bool is_dst, string abbrev)
  888. {
  889. this.Offset = offset;
  890. this.IsDst = is_dst;
  891. this.Name = abbrev;
  892. }
  893. public override string ToString ()
  894. {
  895. return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;
  896. }
  897. #else
  898. }
  899. #endif
  900. }
  901. }
  902. #endif