TimeZoneInfo.cs 33 KB

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