TimeZoneInfo.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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
  29. [assembly:TypeForwardedTo (typeof(TimeZoneInfo))]
  30. #elif NET_3_5 || (NET_2_1 && !INSIDE_CORLIB)
  31. using System.Collections.Generic;
  32. using System.Collections.ObjectModel;
  33. using System.Runtime.Serialization;
  34. using System.Text;
  35. #if LIBC
  36. using System.IO;
  37. using Mono;
  38. #endif
  39. namespace System
  40. {
  41. #if NET_4_0
  42. [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
  43. #endif
  44. [SerializableAttribute]
  45. public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
  46. {
  47. TimeSpan baseUtcOffset;
  48. public TimeSpan BaseUtcOffset {
  49. get { return baseUtcOffset; }
  50. }
  51. string daylightDisplayName;
  52. public string DaylightName {
  53. get {
  54. if (disableDaylightSavingTime)
  55. return String.Empty;
  56. return daylightDisplayName;
  57. }
  58. }
  59. string displayName;
  60. public string DisplayName {
  61. get { return displayName; }
  62. }
  63. string id;
  64. public string Id {
  65. get { return id; }
  66. }
  67. static TimeZoneInfo local;
  68. public static TimeZoneInfo Local {
  69. get {
  70. if (local == null) {
  71. #if LIBC
  72. try {
  73. local = FindSystemTimeZoneByFileName ("Local", "/etc/localtime");
  74. } catch {
  75. try {
  76. local = FindSystemTimeZoneByFileName ("Local", Path.Combine (TimeZoneDirectory, "localtime"));
  77. } catch {
  78. throw new TimeZoneNotFoundException ();
  79. }
  80. }
  81. #else
  82. throw new TimeZoneNotFoundException ();
  83. #endif
  84. }
  85. return local;
  86. }
  87. }
  88. string standardDisplayName;
  89. public string StandardName {
  90. get { return standardDisplayName; }
  91. }
  92. bool disableDaylightSavingTime;
  93. public bool SupportsDaylightSavingTime {
  94. get { return !disableDaylightSavingTime; }
  95. }
  96. static TimeZoneInfo utc;
  97. public static TimeZoneInfo Utc {
  98. get {
  99. if (utc == null)
  100. utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
  101. return utc;
  102. }
  103. }
  104. #if LIBC
  105. static string timeZoneDirectory = null;
  106. static string TimeZoneDirectory {
  107. get {
  108. if (timeZoneDirectory == null)
  109. timeZoneDirectory = "/usr/share/zoneinfo";
  110. return timeZoneDirectory;
  111. }
  112. set {
  113. ClearCachedData ();
  114. timeZoneDirectory = value;
  115. }
  116. }
  117. #endif
  118. private AdjustmentRule [] adjustmentRules;
  119. public static void ClearCachedData ()
  120. {
  121. local = null;
  122. utc = null;
  123. systemTimeZones = null;
  124. }
  125. public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
  126. {
  127. return ConvertTime (dateTime, TimeZoneInfo.Local, destinationTimeZone);
  128. }
  129. public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
  130. {
  131. if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
  132. throw new ArgumentException ("Kind propery of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
  133. if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
  134. throw new ArgumentException ("Kind propery of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
  135. if (sourceTimeZone.IsInvalidTime (dateTime))
  136. throw new ArgumentException ("dateTime parameter is an invalid time");
  137. if (sourceTimeZone == null)
  138. throw new ArgumentNullException ("sourceTimeZone");
  139. if (destinationTimeZone == null)
  140. throw new ArgumentNullException ("destinationTimeZone");
  141. if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
  142. return dateTime;
  143. DateTime utc = ConvertTimeToUtc (dateTime);
  144. if (destinationTimeZone == TimeZoneInfo.Utc)
  145. return utc;
  146. return ConvertTimeFromUtc (utc, destinationTimeZone);
  147. }
  148. public static DateTimeOffset ConvertTime (DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
  149. {
  150. throw new NotImplementedException ();
  151. }
  152. public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
  153. {
  154. return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
  155. }
  156. public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
  157. {
  158. return ConvertTime (dateTime, FindSystemTimeZoneById (sourceTimeZoneId), FindSystemTimeZoneById (destinationTimeZoneId));
  159. }
  160. public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
  161. {
  162. return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
  163. }
  164. private DateTime ConvertTimeFromUtc (DateTime dateTime)
  165. {
  166. if (dateTime.Kind == DateTimeKind.Local)
  167. throw new ArgumentException ("Kind property of dateTime is Local");
  168. if (this == TimeZoneInfo.Utc)
  169. return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
  170. //FIXME: do not rely on DateTime implementation !
  171. if (this == TimeZoneInfo.Local)
  172. return DateTime.SpecifyKind (dateTime.ToLocalTime (), DateTimeKind.Unspecified);
  173. AdjustmentRule rule = GetApplicableRule (dateTime);
  174. if (IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
  175. return DateTime.SpecifyKind (dateTime + BaseUtcOffset + rule.DaylightDelta , DateTimeKind.Unspecified);
  176. else
  177. return DateTime.SpecifyKind (dateTime + BaseUtcOffset, DateTimeKind.Unspecified);
  178. }
  179. public static DateTime ConvertTimeFromUtc (DateTime dateTime, TimeZoneInfo destinationTimeZone)
  180. {
  181. if (destinationTimeZone == null)
  182. throw new ArgumentNullException ("destinationTimeZone");
  183. return destinationTimeZone.ConvertTimeFromUtc (dateTime);
  184. }
  185. public static DateTime ConvertTimeToUtc (DateTime dateTime)
  186. {
  187. if (dateTime.Kind == DateTimeKind.Utc)
  188. return dateTime;
  189. //FIXME: do not rely on DateTime implementation !
  190. return DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc);
  191. }
  192. public static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone)
  193. {
  194. if (sourceTimeZone == null)
  195. throw new ArgumentNullException ("sourceTimeZone");
  196. if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
  197. throw new ArgumentException ("Kind propery of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
  198. if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
  199. throw new ArgumentException ("Kind propery of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
  200. if (sourceTimeZone.IsInvalidTime (dateTime))
  201. throw new ArgumentException ("dateTime parameter is an invalid time");
  202. if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone == TimeZoneInfo.Utc)
  203. return dateTime;
  204. if (dateTime.Kind == DateTimeKind.Utc)
  205. return dateTime;
  206. if (dateTime.Kind == DateTimeKind.Local)
  207. return ConvertTimeToUtc (dateTime);
  208. if (sourceTimeZone.IsAmbiguousTime (dateTime) || !sourceTimeZone.IsDaylightSavingTime (dateTime))
  209. return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
  210. else {
  211. AdjustmentRule rule = sourceTimeZone.GetApplicableRule (dateTime);
  212. return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
  213. }
  214. }
  215. public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName)
  216. {
  217. return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
  218. }
  219. public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
  220. {
  221. return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
  222. }
  223. public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
  224. {
  225. return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
  226. }
  227. public bool Equals (TimeZoneInfo other)
  228. {
  229. if (other == null)
  230. return false;
  231. return other.Id == this.Id && HasSameRules (other);
  232. }
  233. public static TimeZoneInfo FindSystemTimeZoneById (string id)
  234. {
  235. //FIXME: this method should check for cached values in systemTimeZones
  236. if (id == null)
  237. throw new ArgumentNullException ("id");
  238. #if LIBC
  239. string filepath = Path.Combine (TimeZoneDirectory, id);
  240. return FindSystemTimeZoneByFileName (id, filepath);
  241. #else
  242. throw new NotImplementedException ();
  243. #endif
  244. }
  245. #if LIBC
  246. const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
  247. private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
  248. {
  249. if (!File.Exists (filepath))
  250. throw new TimeZoneNotFoundException ();
  251. byte [] buffer = new byte [BUFFER_SIZE];
  252. int length;
  253. using (FileStream stream = File.OpenRead (filepath)) {
  254. length = stream.Read (buffer, 0, BUFFER_SIZE);
  255. }
  256. if (!ValidTZFile (buffer, length))
  257. throw new InvalidTimeZoneException ("TZ file too big for the buffer");
  258. try {
  259. return ParseTZBuffer (id, buffer, length);
  260. } catch (Exception e) {
  261. throw new InvalidTimeZoneException (e.Message);
  262. }
  263. }
  264. #endif
  265. public static TimeZoneInfo FromSerializedString (string source)
  266. {
  267. throw new NotImplementedException ();
  268. }
  269. public AdjustmentRule [] GetAdjustmentRules ()
  270. {
  271. if (disableDaylightSavingTime)
  272. return new AdjustmentRule [0];
  273. else
  274. return (AdjustmentRule []) adjustmentRules.Clone ();
  275. }
  276. public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
  277. {
  278. if (!IsAmbiguousTime (dateTime))
  279. throw new ArgumentException ("dateTime is not an ambiguous time");
  280. AdjustmentRule rule = GetApplicableRule (dateTime);
  281. return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
  282. }
  283. public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
  284. {
  285. if (!IsAmbiguousTime (dateTimeOffset))
  286. throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
  287. throw new NotImplementedException ();
  288. }
  289. public override int GetHashCode ()
  290. {
  291. int hash_code = Id.GetHashCode ();
  292. foreach (AdjustmentRule rule in GetAdjustmentRules ())
  293. hash_code ^= rule.GetHashCode ();
  294. return hash_code;
  295. }
  296. public void GetObjectData (SerializationInfo info, StreamingContext context)
  297. {
  298. throw new NotImplementedException ();
  299. }
  300. //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
  301. private static List<TimeZoneInfo> systemTimeZones = null;
  302. public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
  303. {
  304. if (systemTimeZones == null) {
  305. systemTimeZones = new List<TimeZoneInfo> ();
  306. #if LIBC
  307. string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
  308. foreach (string continent in continents) {
  309. try {
  310. foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
  311. try {
  312. string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
  313. systemTimeZones.Add (FindSystemTimeZoneById (id));
  314. } catch (ArgumentNullException) {
  315. } catch (TimeZoneNotFoundException) {
  316. } catch (InvalidTimeZoneException) {
  317. } catch (Exception) {
  318. throw;
  319. }
  320. }
  321. } catch {}
  322. }
  323. #else
  324. throw new NotImplementedException ("This method is not implemented for this platform");
  325. #endif
  326. }
  327. return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
  328. }
  329. public TimeSpan GetUtcOffset (DateTime dateTime)
  330. {
  331. if (IsDaylightSavingTime (dateTime)) {
  332. AdjustmentRule rule = GetApplicableRule (dateTime);
  333. return BaseUtcOffset + rule.DaylightDelta;
  334. }
  335. return BaseUtcOffset;
  336. }
  337. public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
  338. {
  339. throw new NotImplementedException ();
  340. }
  341. public bool HasSameRules (TimeZoneInfo other)
  342. {
  343. if (other == null)
  344. throw new ArgumentNullException ("other");
  345. if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
  346. return false;
  347. if (this.adjustmentRules == null)
  348. return true;
  349. if (this.BaseUtcOffset != other.BaseUtcOffset)
  350. return false;
  351. if (this.adjustmentRules.Length != other.adjustmentRules.Length)
  352. return false;
  353. for (int i = 0; i < adjustmentRules.Length; i++) {
  354. if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
  355. return false;
  356. }
  357. return true;
  358. }
  359. public bool IsAmbiguousTime (DateTime dateTime)
  360. {
  361. if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
  362. throw new ArgumentException ("Kind is Local and time is Invalid");
  363. if (this == TimeZoneInfo.Utc)
  364. return false;
  365. if (dateTime.Kind == DateTimeKind.Utc)
  366. dateTime = ConvertTimeFromUtc (dateTime);
  367. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
  368. dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
  369. AdjustmentRule rule = GetApplicableRule (dateTime);
  370. DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
  371. if (dateTime > tpoint - rule.DaylightDelta && dateTime <= tpoint)
  372. return true;
  373. return false;
  374. }
  375. public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
  376. {
  377. throw new NotImplementedException ();
  378. }
  379. public bool IsDaylightSavingTime (DateTime dateTime)
  380. {
  381. if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
  382. throw new ArgumentException ("dateTime is invalid and Kind is Local");
  383. if (this == TimeZoneInfo.Utc)
  384. return false;
  385. if (!SupportsDaylightSavingTime)
  386. return false;
  387. //FIXME: do not rely on DateTime implementation !
  388. if ((dateTime.Kind == DateTimeKind.Local || dateTime.Kind == DateTimeKind.Unspecified) && this == TimeZoneInfo.Local)
  389. return dateTime.IsDaylightSavingTime ();
  390. //FIXME: do not rely on DateTime implementation !
  391. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Utc)
  392. return IsDaylightSavingTime (DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc));
  393. AdjustmentRule rule = GetApplicableRule (dateTime.Date);
  394. if (rule == null)
  395. return false;
  396. DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
  397. DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
  398. if (dateTime.Kind == DateTimeKind.Utc) {
  399. DST_start -= BaseUtcOffset;
  400. DST_end -= (BaseUtcOffset + rule.DaylightDelta);
  401. }
  402. return (dateTime >= DST_start && dateTime < DST_end);
  403. }
  404. public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
  405. {
  406. throw new NotImplementedException ();
  407. }
  408. public bool IsInvalidTime (DateTime dateTime)
  409. {
  410. if (dateTime.Kind == DateTimeKind.Utc)
  411. return false;
  412. if (dateTime.Kind == DateTimeKind.Local && this != Local)
  413. return false;
  414. AdjustmentRule rule = GetApplicableRule (dateTime);
  415. DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
  416. if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
  417. return true;
  418. return false;
  419. }
  420. public void OnDeserialization (object sender)
  421. {
  422. throw new NotImplementedException ();
  423. }
  424. public string ToSerializedString ()
  425. {
  426. throw new NotImplementedException ();
  427. }
  428. public override string ToString ()
  429. {
  430. return DisplayName;
  431. }
  432. private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
  433. {
  434. if (id == null)
  435. throw new ArgumentNullException ("id");
  436. if (id == String.Empty)
  437. throw new ArgumentException ("id parameter is an empty string");
  438. if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
  439. throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
  440. if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
  441. throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
  442. #if STRICT
  443. if (id.Length > 32)
  444. throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
  445. #endif
  446. if (adjustmentRules != null && adjustmentRules.Length != 0) {
  447. AdjustmentRule prev = null;
  448. foreach (AdjustmentRule current in adjustmentRules) {
  449. if (current == null)
  450. throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
  451. if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
  452. (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
  453. 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;");
  454. if (prev != null && prev.DateStart > current.DateStart)
  455. throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
  456. if (prev != null && prev.DateEnd > current.DateStart)
  457. throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
  458. if (prev != null && prev.DateEnd == current.DateStart)
  459. throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
  460. prev = current;
  461. }
  462. }
  463. this.id = id;
  464. this.baseUtcOffset = baseUtcOffset;
  465. this.displayName = displayName ?? id;
  466. this.standardDisplayName = standardDisplayName ?? id;
  467. this.daylightDisplayName = daylightDisplayName;
  468. this.disableDaylightSavingTime = disableDaylightSavingTime;
  469. this.adjustmentRules = adjustmentRules;
  470. }
  471. private AdjustmentRule GetApplicableRule (DateTime dateTime)
  472. {
  473. //Transitions are always in standard time
  474. DateTime date = dateTime;
  475. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
  476. date = date.ToUniversalTime () + BaseUtcOffset;
  477. if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
  478. date = date + BaseUtcOffset;
  479. foreach (AdjustmentRule rule in adjustmentRules) {
  480. if (rule.DateStart > date.Date)
  481. return null;
  482. if (rule.DateEnd < date.Date)
  483. continue;
  484. return rule;
  485. }
  486. return null;
  487. }
  488. private static DateTime TransitionPoint (TransitionTime transition, int year)
  489. {
  490. if (transition.IsFixedDateRule)
  491. return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
  492. DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
  493. int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first) % 7;
  494. if (day > DateTime.DaysInMonth (year, transition.Month))
  495. day -= 7;
  496. return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
  497. }
  498. #if LIBC
  499. private static bool ValidTZFile (byte [] buffer, int length)
  500. {
  501. StringBuilder magic = new StringBuilder ();
  502. for (int i = 0; i < 4; i++)
  503. magic.Append ((char)buffer [i]);
  504. if (magic.ToString () != "TZif")
  505. return false;
  506. if (length >= BUFFER_SIZE)
  507. return false;
  508. return true;
  509. }
  510. struct TimeType
  511. {
  512. public readonly int Offset;
  513. public readonly bool IsDst;
  514. public string Name;
  515. public TimeType (int offset, bool is_dst, string abbrev)
  516. {
  517. this.Offset = offset;
  518. this.IsDst = is_dst;
  519. this.Name = abbrev;
  520. }
  521. public override string ToString ()
  522. {
  523. return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;
  524. }
  525. }
  526. static int SwapInt32 (int i)
  527. {
  528. return (((i >> 24) & 0xff)
  529. | ((i >> 8) & 0xff00)
  530. | ((i << 8) & 0xff0000)
  531. | ((i << 24)));
  532. }
  533. static int ReadBigEndianInt32 (byte [] buffer, int start)
  534. {
  535. int i = BitConverter.ToInt32 (buffer, start);
  536. if (!BitConverter.IsLittleEndian)
  537. return i;
  538. return SwapInt32 (i);
  539. }
  540. private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
  541. {
  542. //Reading the header. 4 bytes for magic, 16 are reserved
  543. int ttisgmtcnt = ReadBigEndianInt32 (buffer, 20);
  544. int ttisstdcnt = ReadBigEndianInt32 (buffer, 24);
  545. int leapcnt = ReadBigEndianInt32 (buffer, 28);
  546. int timecnt = ReadBigEndianInt32 (buffer, 32);
  547. int typecnt = ReadBigEndianInt32 (buffer, 36);
  548. int charcnt = ReadBigEndianInt32 (buffer, 40);
  549. if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
  550. throw new InvalidTimeZoneException ();
  551. Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
  552. Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
  553. List<KeyValuePair<DateTime, TimeType>> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
  554. if (time_types.Count == 0)
  555. throw new InvalidTimeZoneException ();
  556. if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
  557. throw new InvalidTimeZoneException ();
  558. TimeSpan baseUtcOffset = new TimeSpan (0);
  559. TimeSpan dstDelta = new TimeSpan (0);
  560. string standardDisplayName = null;
  561. string daylightDisplayName = null;
  562. bool dst_observed = false;
  563. DateTime dst_start = DateTime.MinValue;
  564. List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
  565. for (int i = 0; i < transitions.Count; i++) {
  566. var pair = transitions [i];
  567. DateTime ttime = pair.Key;
  568. TimeType ttype = pair.Value;
  569. if (!ttype.IsDst) {
  570. if (standardDisplayName != ttype.Name || baseUtcOffset.TotalSeconds != ttype.Offset) {
  571. standardDisplayName = ttype.Name;
  572. daylightDisplayName = null;
  573. baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
  574. adjustmentRules = new List<AdjustmentRule> ();
  575. dst_observed = false;
  576. }
  577. if (dst_observed) {
  578. //FIXME: check additional fields for this:
  579. //most of the transitions are expressed in GMT
  580. dst_start += baseUtcOffset;
  581. DateTime dst_end = ttime + baseUtcOffset + dstDelta;
  582. //some weird timezone (America/Phoenix) have end dates on Jan 1st
  583. if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
  584. dst_end -= new TimeSpan (24, 0, 0);
  585. DateTime dateStart, dateEnd;
  586. if (dst_start.Month < 7)
  587. dateStart = new DateTime (dst_start.Year, 1, 1);
  588. else
  589. dateStart = new DateTime (dst_start.Year, 7, 1);
  590. if (dst_end.Month >= 7)
  591. dateEnd = new DateTime (dst_end.Year, 12, 31);
  592. else
  593. dateEnd = new DateTime (dst_end.Year, 6, 30);
  594. TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
  595. TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
  596. if (transition_start != transition_end) //y, that happened in Argentina in 1943-1946
  597. adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
  598. }
  599. dst_observed = false;
  600. } else {
  601. if (daylightDisplayName != ttype.Name || dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds) {
  602. daylightDisplayName = ttype.Name;
  603. dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
  604. }
  605. dst_start = ttime;
  606. dst_observed = true;
  607. }
  608. }
  609. if (adjustmentRules.Count == 0) {
  610. TimeType t = (TimeType)time_types [0];
  611. if (standardDisplayName == null) {
  612. standardDisplayName = t.Name;
  613. baseUtcOffset = new TimeSpan (0, 0, t.Offset);
  614. }
  615. return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
  616. } else {
  617. return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, ValidateRules (adjustmentRules).ToArray ());
  618. }
  619. }
  620. static List<AdjustmentRule> ValidateRules (List<AdjustmentRule> adjustmentRules)
  621. {
  622. AdjustmentRule prev = null;
  623. foreach (AdjustmentRule current in adjustmentRules.ToArray ()) {
  624. if (prev != null && prev.DateEnd > current.DateStart) {
  625. adjustmentRules.Remove (current);
  626. }
  627. prev = current;
  628. }
  629. return adjustmentRules;
  630. }
  631. static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
  632. {
  633. var abbrevs = new Dictionary<int, string> ();
  634. int abbrev_index = 0;
  635. var sb = new StringBuilder ();
  636. for (int i = 0; i < count; i++) {
  637. char c = (char) buffer [index + i];
  638. if (c != '\0')
  639. sb.Append (c);
  640. else {
  641. abbrevs.Add (abbrev_index, sb.ToString ());
  642. //Adding all the substrings too, as it seems to be used, at least for Africa/Windhoek
  643. for (int j = 1; j < sb.Length; j++)
  644. abbrevs.Add (abbrev_index + j, sb.ToString (j, sb.Length - j));
  645. abbrev_index = i + 1;
  646. sb = new StringBuilder ();
  647. }
  648. }
  649. return abbrevs;
  650. }
  651. static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
  652. {
  653. var types = new Dictionary<int, TimeType> (count);
  654. for (int i = 0; i < count; i++) {
  655. int offset = ReadBigEndianInt32 (buffer, index + 6 * i);
  656. byte is_dst = buffer [index + 6 * i + 4];
  657. byte abbrev = buffer [index + 6 * i + 5];
  658. types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
  659. }
  660. return types;
  661. }
  662. static List<KeyValuePair<DateTime, TimeType>> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
  663. {
  664. var list = new List<KeyValuePair<DateTime, TimeType>> (count);
  665. for (int i = 0; i < count; i++) {
  666. int unixtime = ReadBigEndianInt32 (buffer, index + 4 * i);
  667. DateTime ttime = DateTimeFromUnixTime (unixtime);
  668. byte ttype = buffer [index + 4 * count + i];
  669. list.Add (new KeyValuePair<DateTime, TimeType> (ttime, time_types [(int)ttype]));
  670. }
  671. return list;
  672. }
  673. static DateTime DateTimeFromUnixTime (long unix_time)
  674. {
  675. DateTime date_time = new DateTime (1970, 1, 1);
  676. return date_time.AddSeconds (unix_time);
  677. }
  678. #endif
  679. }
  680. }
  681. #endif