TimeZoneInfo.cs 28 KB

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