TimeZoneInfo.cs 27 KB

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